DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Edited on • Originally published at how-to.dev

2 1

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

$ npm install --save-dev css-tree
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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

$ ./build.js 

  dist/main.js  722b 

⚡ Done in 16ms
Enter fullscreen mode Exit fullscreen mode

Links

Summary

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay