Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a flag to auto-prefix local css classes when minified #3914

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

chowey
Copy link

@chowey chowey commented Sep 16, 2024

This addresses #3484 by providing an option to prefix css classes when minifying css modules.

I created the --local-css-prefix command line flag, e.g. --local-css-prefix=myapp-. I also exported this through the Javascript API.

You can now do e.g.

await esbuild.build({
  entryPoint: "index.js",
  outdir: "./dist",
  bundle: true,
  format: "esm",
  minify: true,
  localCSSPrefix: "myapp-", // new option
});

With the following input files:

index.js

import classes from "./classes.module.css";

document.getElementById("main").className = classes.localClassWithRedText;

classes.module.css

.localClassWithRedText {
  color: red;
}

This produces the following output files:

dist/index.css

.myapp-o{color:red}

dist/index.js

var e={localClassWithRedText:"myapp-o"};document.getElementById("main").className=e.localClassWithRedText;

@ziemkowski
Copy link

@chowey Any reason to limit this to minified classnames? Local classname collission is still an issue without minification if you use common names such as .btn, .row, .box, .container, etc. which is easy to run into with CSS Modules.

@chowey
Copy link
Author

chowey commented Dec 17, 2024

@ziemkowski If I understand you correctly, your requirement should already work.

So long as your CSS files are correctly identified as CSS modules, local classnames (when minification is disabled) should not be an issue. esbuild already renames them.

See this example. Taking these two files:

.btn {
  color: red;
}
.btn {
  color: blue;
}

they successfully bundle into this one file:

/* a.module.css */
.a_btn {
  color: red;
}

/* b.module.css */
.b_btn {
  color: blue;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants