DEV Community


When Writing a Reason Library with JS Included

Murphy Randle
I’m a professional software writer specialized in Web technologies and engaged in indie application development. I consider myself to be a man of faith. I pursue honesty, integrity, and compassion.
Updated on ・2 min read

I found myself writing some package code in Reason today (specifically, a localforage wrapper). And for various reasons that I won't dip into here, I wanted to vendor some JS code, including the Javascript file in the project, and linking to it with a relative path ./foo.js from my Reason code.

Here's the problem. Bucklescript (the Javascript backend compiler) strips out unnecessary code when it can, so my library wrapping code (which was just a few external declarations) got stripped completely, and the import statement got moved directly into the file that was calling the wrapper library.

This a nice optimization, and works well when the Javascript being wrapped lives inside of node_modules and can be reached from any file in the project without changing the import path. But when using relative imports, it doesn't work out so well.

The Reason Discord channel informed me that if the library includes an .rei file, or a Reason interface file, the wrapping code won't be compiled away, and the relative import will stay in the file where it was defined, instead of getting moved to the call site.

This should enable Reason library authors to include raw Javascript that's linked using relative paths in their Reason projects.

There's another method, too, suggested in the Discord channel:

Just copy all of the Javascript you want to include, and paste it into a [%%bs.raw ] block at the top level of some Reason file. That will include all of the JS directly into the compiled output of that file, and the author won't need to worry about relative imports at all after that.

Discussion (3)

thangngoc89 profile image
Khoa Nguyen

It’s bucklescript who strips out the unused code. And you have inconsistent usuages of Reason and ReasonML

mrmurphy profile image
Murphy Randle Author

Thanks! Fixed now.