How to set up CSS Modules with esbuild

In this article, I'll show how to configure CSS Modules with esbuild.

CSS Modules

It is a technic of making our styles scoped locally. I first encountered it while working on this SolidJS + esbuild. My understanding is that it's popular among developers using react.

Code

My code is pretty simples. src/style.module.css:

.test {
  color: #66f;
}

src/index.js:

import styles from "./style.module.css";

const header = document.createElement("h1");

header.innerHTML = "Hello world";
header.className = styles.test;

document.body.appendChild(header);

Output

This is combined in a way that ensures no css class collision:

<style>
._test_1f4jo_1 {
    color: #66f;
}
</style>
...
<h1 class="_test_1f4jo_1">Hello world</h1>

Dependencies

Esbuild needs a plugin to support CSS modules. On the plugin list, there are 2 listed. I used esbuild-css-modules-plugin here. The dependencies needed to run it all successfully:

$ npm install --save-dev esbuild-css-modules-plugin esbuild

An additional dependency is needed to address a tiny dependency issue:

$ npm install --save-dev css-tree

esbuild

For using a plugin with esbuild, we need a build script. build.js:

#!/usr/bin/env node

const cssModulesPlugin = require("esbuild-css-modules-plugin");

require("esbuild")
  .build({
    logLevel: "info",
    entryPoints: ["src/index.js"],
    bundle: true,
    outfile: "dist/main.js",
    plugins: [cssModulesPlugin()],
  })
  .catch(() => process.exit(1));

If you run chmod +x build.js, you will be able to run it:

$ ./build.js 

  dist/main.js  722b 

⚡ Done in 16ms

Links

Video course

You can check out my course about esbuild.

Summary

In this article, we have seen how to configure CSS Modules with esbuild.