How to manage CSS with esbuild

In this article, I'll show how to add styling to our application. The starting point is where we left in step 2.

JS

To start, let's replace our dummy JS with code that at least put something on the screen. I go with vanilla JS because frameworks tend to complicate the esbuild setup. Let's set src/index.js to:

import "./style.css";

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

header.innerHTML = "Hello world";

document.body.appendChild(header);
  • import "./style.css";- by default, esbuild has CSS loader set up, but styles are not included in JS bundle. Before we get to it, we have to add the ./style.css because now it's failing to build
  • const header = ... & the following lines - simple code to add element to the page. By doing it in JS, by one glimpse, we can tell if the JS is working or not.

CSS

The styling goes to ./src/style.css:

body {
  color: #66f;
}

If we build our application with npm run build or start the server with npm run start, we will see the header without the color. That's because styles are emitted to style file - with the same name as our bundle, but with .css extension.

HTML

To include the styling we have to add:

    <link rel="stylesheet" type="text/css" href="./main.css"/>

With this in place, the application should look like this:

styled-application.png

Links

The repo, branch step 3.

You can check out my video course about esbuild.

Summary

In this article, we have seen how to add styling to our esbuild application. If you are interested in the hearing when there is a new part ready, you can sign up: