How can I load an external JavaScript file in Pure-Script?
The foreign import statements all inline the javascript code, but I want to load them from an external file.
How can I load an external JavaScript file in Pure-Script?
The foreign import statements all inline the javascript code, but I want to load them from an external file.
You can wrap the standard global commonjs require
function using an ffi.
foreign import require :: forall a. String -> a
You can then import a library like so
-- Tell the compiler the structure of what you're importing.
type MyLibrary = {
add :: Number -> Number -> Number
}
-- Call the require function and import the library.
-- We need an explicit type annotation so the compiler know what's up
myLib = require './mylib' :: MyLibrary
main = do
let x = myLib.add 1 2
doSomethingWith x
Keep in mind that purescript assumes the functions in the external library have been curried. If you need to call a function that takes multiple arguments, you'll need a bit more boilerplate - i.e. using mkFn.
See here for more detail on how to do that.
https://github.com/purescript/purescript/wiki/FFI-tips
Side note - 'require' is implemented as a pure function in this example, however if the library you're using executes side-effects during import (Which is unfortunately not uncommon), you should instead define a requireEff
function that wraps the import in the Eff monad.