3
votes

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.

1
Why not just include the JavaScript file in your page, or use the FFI to load the JavaScript file using your module loader?Phil Freeman
I am not in a browser environment. I plan to generate javascript code in a haskellish way. I have got a javascript file with objects and helper functions in it. I would like to reference those js objects in a prescript app. But I think this is not possible because in this case prescript wourl have to parse the external js file, and build up an internal representation of all the objects. I am very new to purescript and I think I misunderstand its working a bit. Sure I can inline all the code with foreign import but I thought I could Import an existing js library from an external fileagreif
You can definitely give types to your functions using the FFI, and you probably don't need to write inline JS, but that depends on the structure of your library. I'd suggest looking at one of the many libraries in the GitHub purescript-contrib organization.Phil Freeman

1 Answers

4
votes

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.