Following the docs here: https://nim-lang.org/docs/backends.html#backends-the-javascript-target
I have the following code in fib.nim
proc fib(a: cint): cint {.exportc.} =
if a <= 2:
result = 1
else:
result = fib(a - 1) + fib(a - 2)
If I run nim js -o:fib.js fib.nim
then it compiles it to JS.
How do I then run fib from nodejs? In the example, its an html file and a browser, but on node, I cant figure out how to import the fib function. It looks like the .js file is missing the exports
. How can I build the nim module so that nodejs can import it?
I can't find a built in way of compiling a nim module to a js module. The workaround is to import the module
object and export procs.
import jsffi
var module {.importc.}: JsObject
proc fib*(a: cint): cint =
if a <= 2:
result = 1
else:
result = fib(a - 1) + fib(a - 2)
module.exports.fib = fib
The above can be expressed as a macro:
import macros, jsfii
var module {.importc.}: JsObject
macro exportjs(body: typed) =
let bodyName = body.name.strVal
result = newStmtList(
body,
newAssignment(
newDotExpr(newDotExpr(ident"module", ident"exports"), ident(bodyName)),
ident(bodyName)
)
)
proc fib*(a: cint): cint {.exportjs.} =
if a <= 2:
result = 1
else:
result = fib(a - 1) + fib(a - 2)
This repo came up while looking up solutions: https://github.com/nepeckman/jsExport.nim
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With