codehz/css-in-bun

Feature request: one CSS bundle per entrypoint

spirobel opened this issue · 2 comments

// build.ts
import { getGeneratedCss } from "css-in-bun/build";

const res = await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "dist",
});

const css = getGeneratedCss();

will put all the css in one file.

It should be possible to split the CSS into multiple files if there are multiple entrypoints.

The outcome will be that there is a CSS bundle for every BuildArtifact according to the Bun.build output:

interface BuildOutput {
  outputs: BuildArtifact[];
  success: boolean;
  logs: Array<BuildMessage | ResolveMessage>;
}

interface BuildArtifact extends Blob {
  path: string;
  loader: Loader;
  hash?: string;
  kind: "entry-point" | "chunk" | "asset" | "sourcemap";
  sourcemap?: BuildArtifact;
}

https://bun.sh/docs/bundler

bun currrently has no API to make a direct relationship between source input file and BuildArtifact, right?
But there is another way: 1. use the sourcemap 2. use grep / regex to find the css class names in the finished BuildArtifacts and then cut all the ones that cant be found to produce the respective smaller bundle for each BuildArtifact.

There are several problems with this.

  1. This project (currently) follows the design of style9 (https://github.com/johanholmerin/style9/blob/master/docs/Background.md#optimized-output), which is to generate a single css file and automatically remove duplicates (aka atomic css). It may offer multiple options in the future, but it's not an immediate goal.
  2. This project (only) use macro to convert css definitions, no plugin is used. Currently, bun does not provide the ability to access the macro context in the plugin system (or reverse). And the macro has no way of knowing what source file is being "executed". Even if I want to change the design, there are many difficulties here, more than listed above.

Just read up on atomic CSS and its effect on CSS file size. Seems like it reduces file size so much that it is not worth the effort to further reduce it by splitting it into multiple files.
This is amazing! Thanks for your work. I also think its cool how you turned the styles into an object instead of a function. That makes it super easy to use them directly. Nice improvement over the style9 API.