CSS Nesting Syntax Conversion
snippetCSS nesting syntax is not universally supported yet, so we can either avoid or convert it. For the latter I’ve come to appreciate esbuild.
article {
h2 {
color: cadetblue;
}
}$ esbuild --supported:nesting=false ./sample.css
article h2 {
color: cadetblue;
}Sometimes we might want to go a little further, using a JavaScript file as our entry point – which can be particularly useful for front-end widgets:
import "./sample.css";
import "./sample.js";customElements.define("sample-component", class extends HTMLElement {
// …
});$ esbuild --bundle --format=esm --supported:nesting=false \
--outdir=./dist ./component.jsThis will generate two independent files, dist/component.js and
dist/component.css, clearly separating JavaScript and CSS (i.e. there’s no
magic integration happening here).
Note that bundling changes the way assets are handled, so we might need to specify a loader:
article {
background-image: url(./bg.png);
}$ esbuild … --bundle --loader:.png=copy --outdir=./distThis will generate a fingerprinted copy of bg.png within dist and make sure
that the reference within CSS is transformed accordingly.