# How to set up CSS Modules with esbuild

In this article, I'll show how to configure [CSS Modules](https://github.com/css-modules/css-modules) with [esbuild](https://esbuild.github.io/).

# CSS Modules
It is a technic of making our styles scoped locally. I first encountered it while working on this [SolidJS + esbuild](https://how-to.dev/how-to-build-solidjs-application-with-esbuild). My understanding is that it's popular among developers using react.

# Code

My code is pretty simples. `src/style.module.css`:
```CSS
.test {
  color: #66f;
}
```

`src/index.js`:
```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:
```html
<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](https://github.com/esbuild/community-plugins), there are 2 listed. I used [esbuild-css-modules-plugin](https://github.com/indooorsman/esbuild-css-modules-plugin) here. The dependencies needed to run it all successfully:
```sh
$ npm install --save-dev esbuild-css-modules-plugin esbuild
```

An additional dependency is needed to address a tiny dependency issue:
```sh
$ npm install --save-dev css-tree
```

# esbuild
For using a plugin with esbuild, we need a build script. `build.js`:
```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:
```sh
$ ./build.js 

  dist/main.js  722b 

⚡ Done in 16ms
```

# Links
* [example repo](https://github.com/how-to-js/esbuild-css-modules)
* [build output in acction](https://how-to-js.github.io/esbuild-css-modules/dist)

# Video course
You can check out my [course about esbuild](https://bit.ly/esbuild-course).

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

%%[esbuild]
