DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Marcin Wosinek
Marcin Wosinek

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

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.

Top comments (0)

Our newest Hackathon

Join the DEV x MongoDB Atlas Hackathon 2022 and use your ingenuity and creativity to build an application using MongoDB's cloud based developer data platform, MongoDB Atlas.

→ Get Started