Welcome! We notice you're using an outdated browser, which will result in a degraded experience on this site. Please consider a modern, fully supported browser.

webbureaucrat

The articles are just window-dressing for code snippets I want to keep.

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/"),
    }
};

This folder 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"
}

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.

I write to learn, so I welcome your constructive criticism. Report issues on GitLab.

← Home