How to use npm packages with ReasonML?

3.5k views Asked by At

I'm quite experienced with ReactJS and now I'm trying to learn ReasonML. But one thing that I've been struggling to understand, is how to import npm packages with React/Reason.

The instructions on the website are kinda unclear to me (https://reasonml.github.io/guide/javascript/interop/).

So, if I have a React/Reason project and want to use a npm package, how do I do it? How do I import it, using Reason lang?

1

There are 1 answers

6
glennsl On BEST ANSWER

First off, thanks for the feedback! I'll make sure to get this improved.

Now, to be able to use a javascript library published on npm, you'll need to either find or make some bindings for it, as a bridge between Reason/BuckleScript and JavaScript. Ideally, the bindings you need have already been written (or generated) and published to npm, but in case it hasn't you'll have to write them yourself.

Most readily available bindings are listed in redex, the package index, and will include instructions on how to use it. But if they don't, all you need to do is run npm install --save <package-name>, as usual, then add the package name to the bs-dependencies array in bsconfig.json (see also the BuckleScript manual). Make sure to run bsb -make-world to get the new dependency built, then you should be able to use the modules exported by the bindings directly.

If there are no bindings, and you want to make your own, all you need to do is add the javascript package as normal using npm install --save <pacakge-name>, then just start writing externals. How to do so is described in the BuckleScript manual. You may also find my FFI cheatsheet useful.

Lastly, you're welcome to join us on our Discord where there's lots of friendly people eager to help!