DEV Community

webbureaucrat
webbureaucrat

Posted on • Originally published at webbureaucrat.gitlab.io on

Setting Up Webpack for ReScript

As much as I strongly prefer ES6 modules, using them with ReScript (formerly BuckleScript / ReasonML) and ServiceWorkers just isn't practical right now. I'm writing this article so that I can easily grab the configuration the next time I need it. This is a beginner's guide because I am a webpack beginner, and, well, everyone is a ReScript beginner right now.

Some basic setup

  1. Open your bsconfig.json and set the module property of the package-specs object to "commonjs" if it is not already set.
  2. Install webpack locally by running npm i webpack webpack-cli.

Configuring webpack

It's important to note for your configuration where your javascript .bs.js files are output, and this is controlled by the in-source property of the same package-specs object in bsconfig.json. This guide assumes in-source is false (because, quite frankly, that's my preference) but it means that the .bs.js outputs get buried in a deeply nested folder structure.

This is a sample webpack.config.js file based on those assumptions.

const path = require('path');
module.exports = 
{ 
    entry: 
    { 
        index: "./lib/js/src/index.bs.js", 
        about: "./lib/js/src/about.bs.js" 
    }, 
    output: 
    { 
        filename: "[name].js", 
        path: path.resolve(__dirname, "dist/"), 
    }
};
Enter fullscreen mode Exit fullscreen mode

This configuration assumes that we should process two output files index.bs.js and about.bs.js (and their dependencies) and then outputs each bundled file by their name ("index" and "about") into the folder called dist/. The resulting bundles are dist/index.js and dist/about.js.

Including webpack in the build

You're welcome to run npx webpack any time you want to regenerate your bundled files, but it's a good automation practice to add it to your build command like so:

"scripts": 
{ 
    "build": "npx bsb -make-world && npx webpack", 
    "start": "npx bsb -make-world -w", 
    "clean": "npx bsb -clean-world"
}
Enter fullscreen mode Exit fullscreen mode

In conclusion

I'm still not a fan of script bundlers and avoid them wherever possible, but when it's not possible, it's nice to have a configuration pasta on hand. In a future article, I'll talk about my main use for webpack: ServiceWorkers.

Top comments (0)