This is a short one, folks!

Eleventy's WebC plugin allows for "component-driven, cache-friendly page-specific JavaScript", meaning, if a component is used on a page and it incorporates JavaScript, that block of code will only be loaded for that specific page.

That's great and all, but once you've written component level JavaScript, it just sits there in all it's glory, full of indentations, line breaks and long variable names. We need to minify it to squeeze every little (K)Byte out of it to save some bandwidth.

The WebC plugin in itself depends on the Eleventy plugin bundle, which has a transforms config option. transforms allows us to manipulate the content being parsed by the plugin bundle. We can, for example, call the minify method from the terser package, if the content's type is, you guessed it, JavaScript.

const pluginBundle = require("@11ty/eleventy-plugin-bundle");
const { minify } = require("terser");

module.exports = (eleventyConfig) => {
eleventyConfig.addPlugin(pluginBundle, {
transforms: [
async function (content) {
if (this.type === "js" && process.env.ELEVENTY_ENV === "production") {
const minified = await minify(content);
return minified.code;
}
return content;
},
],
});
};