Using LightningCSS with Eleventy 3
I like to use Stephanie Eckles' excellent LightningCSS plugin for Eleventy projects. I made a couple of tweaks to get it to work the way I wanted, which I am noting here.
LightningCSS has several useful features, but the main one that interests me is the bundler. I want to be able to break my CSS up into partial stylesheets and import the partials inline into a single style.css file. This is one of the key features of Sass and LightningCSS allows me to do this as well.
/* css/style.css */
/* Note the CSS partials are all prefixed with "_" */
@import "_reset.css";
@import "_theme.css";
@import "_typography.css";
@import "_layout.css";
LightningCSS will concatenate all the import files into a single style.css file at build time. Then the style.css file is automatically copied over to a css folder in the final output (build) folder. I can then link to the single CSS file.
<head>
...
<link rel="stylesheet" href="./css/style.css" />
...
</head>
Here are a few notes about using the plugin with Eleventy 3:
Use ESM syntax in eleventy.config.js
Eleventy 3 by default uses ESM syntax, replacing CommonJS syntax. But the plugin README uses CommonJS for inclusion in eleventy.config.js. Here is the setup using ESM:
// eleventy.config.js
import lightningCSS from "@11tyrocks/eleventy-plugin-lightningcss";
export default async function (eleventyConfig) {
// If you already have a config, add just the following line
eleventyConfig.addPlugin(lightningCSS);
};
LightningCSS configuration options
By default LightningCSS will minify CSS and un-nest native CSS nesting. I prefer to override some of the defaults like this:
export default async function (eleventyConfig) {
// Override some of the LightningCSS defaults
eleventyConfig.addPlugin(lightningCSS, {
minify: false,
nesting: false,
customMedia: false,
});
};
Update browserslist in package.json
Lightning CSS also uses browserslist to determine whether or not it will transpile modern CSS features into older syntax.
The LightningCSS plugin by default has very conservative browserslist default targets of > 0.2% and not dead. I want to use CSS features through Baseline 2023, so I added a browerslist member to the bottom of package.json.
{
"name": "my-eleventy-project",
"version": "1.0.0",
"dependencies": { ... },
"browserslist": [
"baseline 2023"
]
}
No passthrough file copy needed
Note that the plugin automatically copies the final constructed style.css file into the output folder. You don't need a passthrough file copy statement in eleventy.config.js for your CSS file!
This setup is working great for me, hopefully it will work for you as well.