日本語

Bundling CSS into One File with Bun’s bun build

​​Bun​CSS,TypeScript

When you pass a CSS file to bun build, the files loaded with @import are combined into one CSS file. When you write import "./xxx.css" in TypeScript, a single file containing only the CSS is output separately from the JavaScript. Up to this point, Bun alone is enough, without installing Vite, PostCSS, or similar tools.

This is about the case where you have CSS split into files for reset, layout, and buttons, and you want to combine them into one file before deploying the site so the page loads only one stylesheet. I actually ran the build in a test environment and checked the contents and size of the output.

Note

The test environment was Ubuntu 24.04 (x86_64) with Bun 1.4.4. For checking colors in the browser, I used Chromium from Playwright 1.63.0. I did not test CSS Modules, plugins such as Tailwind CSS, builds that use HTML as the entry point, calling Bun.build() from JavaScript, --css-chunking, Windows, or macOS. For the official documentation, I checked the source files for the version I used (tag bun-v1.4.4) on GitHub, and the links point there.

Pass a CSS file with @import statements to bun build

Create one entry file that lists the CSS files to combine with @import. The files are arranged like this:

text
src/
├── styles.css            ← 入口
├── css/
│   ├── reset.css
│   ├── colors.css
│   ├── layout.css
│   └── components/
│       └── button.css
└── img/
    └── paw.png
css
/* src/styles.css */
/* Entry point for the site-wide styles */
@import "./css/reset.css";
@import "./css/colors.css";
@import "./css/layout.css";
@import "./css/components/button.css";

button.css uses color variables, so it also imports colors.css, and it uses the nested &:hover syntax (CSS Nesting). layout.css uses url() to set a small image as a background.

css
/* src/css/components/button.css */
@import "../colors.css";

.button {
  color: white;
  background: var(--main);

  &:hover {
    background: var(--accent);
  }
}
css
/* src/css/layout.css (excerpt) */
.header {
  display: flex;
  align-items: center;
  background: url("../img/paw.png") no-repeat left center;
}

Pass the entry file styles.css to bun build, and set the output directory with --outdir.

text
$ bun build ./src/styles.css --outdir ./dist
Bundled 6 modules in 4ms

  styles.css  0.68 KB  (asset)

Only one file, styles.css, was written to dist, and it was 681 bytes. The css loader section of the official documentation describes how @import and url() are followed and combined into a single .css file. The output looked like this:

css
/* src/css/reset.css */
*, *:before, *:after {
  box-sizing: border-box;
}

body {
  margin: 0;
  line-height: 1.6;
}

/* src/css/layout.css */
.container {
  max-width: 960px;
  margin: 0 auto;
  padding: 0 16px;
}

.header {
  display: flex;
  background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAABvFaqvAAAAHklEQVR42mNgOPGCOmjUoFGDRg0aNWjUoFGDBt4gAM+czC4FOcdMAAAAAElFTkSuQmCC") 0 no-repeat;
  align-items:  center;
}

/* src/css/colors.css */
:root {
  --main: #00c8e8;
  --accent: #d85878;
}

/* src/css/components/button.css */
.button {
  color: #fff;
  background: var(--main);
}

.button:hover {
  background: var(--accent);
}

/* src/styles.css */

Each file gets a comment with its original file name, such as /* src/css/reset.css */. Compared with the original files, these changes were made:

  • The nested &:hover was rewritten as a normal selector, .button:hover.
  • white became #fff, and *::before became *:before.
  • The 87-byte paw.png was not written as a separate file. It was embedded in the CSS as a data: URL.
  • colors.css is imported in two places, in button.css and in the entry file, but it appears only once in the output. Its position moved from the second place in the entry file to after layout.css (just before button.css).

The official CSS documentation says that rewriting nested selectors as normal selectors and converting for older browsers are done by default. The change in the position of colors.css, which is the last item above, affects variable overrides, so I look at it in detail in a later section.

Set the file name with –outfile and compress with –minify

If you want to choose the output file name yourself, use --outfile instead of --outdir.

text
$ bun build ./src/styles.css --outfile ./out/site.css
Bundled 6 modules in 4ms

  site.css  0.68 KB  (asset)

This created out/site.css, a 681-byte file identical to dist/styles.css.

For production, adding --minify removes the whitespace, the line breaks, and the file-name comments.

text
$ bun build ./src/styles.css --minify --outdir ./dist-min
Bundled 6 modules in 3ms

  styles.css  455 bytes  (asset)
css
*,*:before,*:after{box-sizing:border-box}body{margin:0;line-height:1.6}.container{max-width:960px;margin:0 auto;padding:0 16px}.header{display:flex;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAABvFaqvAAAAHklEQVR42mNgOPGCOmjUoFGDRg0aNWjUoFGDBt4gAM+czC4FOcdMAAAAAElFTkSuQmCC) 0 no-repeat;align-items: center}:root{--main:#00c8e8;--accent:#d85878}.button{color:#fff;background:var(--main)}.button:hover{background:var(--accent)}

Here are the sizes. The gzip sizes were produced with gzip -9.

Output As is After gzip
Without --minify 681 bytes 447 bytes
With --minify 455 bytes 367 bytes

Files referenced with url() under 128KiB were inlined into the CSS

Whether a file referenced with url() was embedded in the CSS or written as a separate file depended on its size. I prepared two files, one of 131,071 bytes and one of 131,072 bytes (128KiB). Both had a .png extension, but they were not actual images. I referenced them with url().

css
.a {
  background: url("./small.png");
}

.b {
  background: url("./large.png");
}
text
$ bun build ./img-size/images.css --outdir ./img-size/dist
Bundled 3 modules in 5ms

  images.css          174.89 KB  (asset)
  large-tqh4dgp3.png  131.1 KB   (asset)

small.png, at 131,071 bytes, was embedded in the CSS as base64, and the CSS grew to 174,893 bytes. large.png, at 131,072 bytes, was copied to the output directory with a hash in its name, as large-tqh4dgp3.png, and the reference in the CSS was rewritten to url("./large-tqh4dgp3.png").

This boundary is the result of testing with Bun 1.4.4. The official documentation does not say at what size the behavior changes. If you reference large files with url(), the CSS becomes larger by that amount, so check the CSS size after the build.

CSS imported from TypeScript also gets bundled into one file

I also tested the case where each component's TypeScript file imports that component's CSS.

ts
// src/main.ts
import "./css/reset.css";
import { renderHeader } from "./ts/header";
import { renderButton } from "./ts/button";

document.body.innerHTML = renderHeader() + renderButton("なでる");
ts
// src/ts/header.ts
import "../css/layout.css";

export function renderHeader(): string {
  return '<header class="header container">それなら猫の手で</header>';
}
ts
// src/ts/button.ts
import "../css/components/button.css";

export function renderButton(label: string): string {
  return `<button class="button">${label}</button>`;
}
text
$ bun build ./src/main.ts --outdir ./dist-js
Bundled 8 modules in 4ms

  main.js   320 bytes  (entry point)
  main.css  0.66 KB    (asset)

The CSS loaded from the three files was combined into one file, main.css. Its order matched the entry-file case (reset.css, layout.css, colors.css, button.css). It was 658 bytes, which is smaller because it does not include the trailing /* src/styles.css */ comment and the blank lines around it.

On the other hand, main.js did not contain any code to load main.css.

js
// src/ts/header.ts
function renderHeader() {
  return '<header class="header container">それなら猫の手で</header>';
}

// src/ts/button.ts
function renderButton(label) {
  return `<button class="button">${label}</button>`;
}

// src/main.ts
document.body.innerHTML = renderHeader() + renderButton("なでる");

With this build output, you need to add a <link rel="stylesheet"> to the HTML <head> yourself to load main.css. I created an HTML file that loads main.css and main.js side by side and opened it in Chromium. The button's background color was the value of --main in main.css, rgb(0, 200, 232).

html
<link rel="stylesheet" href="../dist-js/main.css">
<script type="module" src="../dist-js/main.js"></script>

Importing the same file in two places breaks variable overrides

In the first build, the position of colors.css had moved to a later place. This is a problem when a CSS file loaded later overrides variables.

In the following example, colors.css sets --main to a light cyan, and then theme.css overrides it with a darker cyan. button.css also @imports colors.css.

css
/* styles.css (entry point) */
@import "./colors.css";
@import "./theme.css";
@import "./button.css";
css
/* colors.css */
:root {
  --main: #00c8e8;
}
css
/* theme.css */
/* Overrides --main with a darker theme color */
:root {
  --main: #067a98;
}
css
/* button.css */
@import "./colors.css";

.button {
  color: white;
  background: var(--main);
}

After the build, colors.css had moved after theme.css.

css
/* order/broken/theme.css */
:root {
  --main: #067a98;
}

/* order/broken/colors.css */
:root {
  --main: #00c8e8;
}

/* order/broken/button.css */
.button {
  color: #fff;
  background: var(--main);
}

/* order/broken/styles.css */

When declarations with the same specificity conflict, the one written later wins ("source order" in MDN's cascade guide). So --main went back to the light cyan #00c8e8. I loaded the built CSS in Chromium and read the button's background color with getComputedStyle. It was rgb(0, 200, 232) (#00c8e8).

The override failure was not caused by bun build. I loaded the original styles.css directly into Chromium with a <link>, without building, and the background color was the same rgb(0, 200, 232). The cause is importing the same file in two places. The bun build output had the same order that the browser would use when reading the original files.

To fix this, remove @import "./colors.css"; from button.css, so that colors.css is imported only once, in the entry file styles.css. When I rebuilt without changing the entry file, the output order became colors.css, theme.css, button.css, and the button's background color became rgb(6, 122, 152) (#067a98).

Screenshot of buttons from two builds. The version where button.css also @imports colors.css shows the light cyan color. The version where @import is only in the entry styles.css shows the darker cyan color.
Top: @import in two places. Bottom: @import only in the entry file. The top does not show the darker theme color.

When you collect the @import statements for shared files in one place, in the entry file, the bun build output kept the order written in the entry file. If component CSS also @imports shared files, as in this example, the output order changed from the entry file's order. If you find that overrides don't work, open the output CSS and check the order of the file-name comments.

Build errors and @import that stays in the output

If you write @import after other rules, the build stops with an error and no files are written (exit code 1). I ran these tests in a project placed at the example path /path/to/app, so the paths in the output are as shown.

text
$ bun build ./order/late.css --outdir ./order/dist-late
5 | @import "./colors.css";
           ^
error: @import rules must come before any other rules except @charset and @layer
    at /path/to/app/order/late.css:5:8

The message means that @import must come before any rules other than @charset and @layer. When I misspelled a file name, the build also stopped, with a Could not resolve error.

text
$ bun build ./src/missing.css --outdir ./dist-missing
2 | @import "./css/missing.css";
    ^
error: Could not resolve: "./css/missing.css"
    at /path/to/app/src/missing.css:2:1

When I wrote a URL starting with https://, such as a Google Fonts URL, in the form @import url("https://…"), it was not inlined. It stayed at the top of the output, with url() removed so it became @import "https://…".

css
@import "https://fonts.googleapis.com/css2?family=Noto+Sans+JP&display=swap";

/* order/colors.css */
:root {
  --main: #00c8e8;
}

/* order/ext.css */

​Posted by 86