Use the pure functions defined in your elm code in your Node.js server in a synchronous way!
Only available on Linux right now.
✨ Install on linux ✨
Say you have some wonderful elm code, computing sums and storing specific data:
-- src/Main.elm
module Main exposing (answer, sum)
answer : Int
answer = 42
sum : { a: Float, b: Float} -> Float
sum data =
data.a + data.b
You just have to run:
elm2node src/Main.elm
This will produce an elm.js
file which is a valid Node.js module. Try it out in
the Node.js repl:
$ node
> myModel = require('./elm.js')
{ answer: 42, sum: [Function: sum] }
> myModel.answer
42
> myModel.sum({a: 5, b: 7})
12
The exposed values do have some restrictions:
- only "static" values or functions with one argument can be exposed
- the only accepted types in exposed values are:
Int
,Float
,String
,Maybe
,Records
,List
,Array
,Json.Encode.Value
- exposed user defined types are silently ignored.
Short answer: no.
More useful answer: you can simulate the mutiple arguments using an "JS object/elm record"
as argument. For example, if you want your function sum two floats a
and b
, you can
define:
sum : { a: Float, b: Float} -> Float
sum data =
data.a + data.b
In the Node.js server side, you'd have to write something like:
myModule.calc({a: 5, b: 7})
However, as recommended in the elm documentation,
consider using a Json.Encode.Value
as type and use a custom decoder to handle errors.
If you omit the type annotation in the top level answer = 42
declaration,
the type of answer
will be inferred as number
which is not an exportable type.
Add a type annotation like (it is a good habit to have, anyway!):
answer : Int
answer = 42
Yes! This tool was built from the official elm 0.19.1 compiler, just modifying how the compiler deal with exposed functions for the files given as arguments and removing useless stuff for our purpose (reactor, publishing packages...).