ReasonML is a lot of things, including but not limited to:
- The OCaml language with a JS-like syntax
- An awesome way to build type-safe React apps
To accomplish that last trick, there’s a library called reason-react, and the getting started guide shows two easy ways to build a working React application in a single command. Both of them use webpack and have different advantages; while the recommended approach is simple and lightweight, the alternative uses create-react-app to give you a fully featured development experience, including hot module replacement, small production builds, and a whole lot more. But to me, both of these solutions seem a little magical, so I’d like to demystify things a bit.
I think the best way to do that is to build a reason-react app from scratch, much like we did with React apps beforecreate-react-app blessed us with great defaults, but without the extra work of configuring webpack. My goal is to keep things lightweight like the preferred approach, and to add in hot module replacement. We’ll be using the Parcel bundler for this, and we’ll have to learn some basic Bucklescript FFI in order to accomplish the HMR. Let’s bundle up!
If you want to skip the guide and go straight to the code, check out the repo. Otherwise, read on!
Step 1: Get Buckled
We need to initialize a basic Bucklescript app first. You’ll need bs-platform for this, which has some system dependencies, like a c compiler and make. Once you have it installed, you can create an app:
$ bsb -init sparcely-unreasonable -theme basic-reason
Open up your editor in the new directory and you should see something like this.
There’s one file in our `src/` folder, called Demo.re. This file calls the Js.log function which is a bit of interop that compiles to `console.log`. You can take my word for that, but instead, let’s prove it by building the project. Go to the console and run:
$ yarn build
By the way, I’m using yarn for this. Feel free to use npm commands instead!
Now back in the code editor, notice that there’s a Demo.bs.js file with a console.log statement corresponding to the Js.log statement. This is the output of compiling Demo.re.
Since we now have a `.js` file, we can run it with node.js, or from within a browser. We want the latter, and we want to use parcel-bundler to do it, which starts with an installation step.
$ yarn add --dev parcel-bundler
We can now bundle and serve our application:
yarn parcel index.html
One neat thing about parcel is that it doesn’t require configuration. Webpack would require you to declare an entry point and a bundle name in a config file, and the `index.html` file would have a tag that references the name of your bundle. With parcel, the