How to minify your Eleventy build
Benjamin Rancourt
Posted on October 16, 2020
If you look at the output of your Eleventy build , you will see that your code is still very readable , your templates have been only injected with your data. All spacing and comments have been conserved. It is great for debugging purposes, but not so much for your visitors, as they will load more bytes to use your website. 😞
But what if we could remove all those characters that do not improve the user experience? That technique is named minification and even if Eleventy does not support natively this functionality, you only need a couple of lines to add it to your process build. 🤖
Eleventy provide us with a configuration named Transforms that allow us to modify a template’s output. With that option, we can define a function that will take the generated code and minify it before the file is written. It is exactly what we needed. 😊
Eleventy even provide an example to minify an HTML file in their documentation. I reproduced it below, along with some minor changes:
You can now minify HTML files, but if you want to do the same thing to other types, like JSON
or XML
, this example can only inspire you…
In order to ease your pain, I recently created the @sherby/eleventy-plugin-files-minifier npm package! This plugin take care to register a transform function that can minify the following types automatically for you:
html
json
xml
xsl
webmanifest
To add this plugin, you only need to install the dependency with npm
npm install @sherby/eleventy-plugin-files-minifier --save-dev
and to add the plugin into your Eleventy config file (.eleventy.js
)
const eleventyPluginFilesMinifier = require("@sherby/eleventy-plugin-files-minifier");
module.exports = (eleventyConfig) => {
eleventyConfig.addPlugin(eleventyPluginFilesMinifier);
};
Pretty simple, right?
The current implementation checks at the file extension to choose how to correctly minify it. The file also needs to be written by Eleventy. 🧱
If your build minify other types and if you want to share it with the community, feel free to make a Pull Request to the code repository on GitHub! I made sure to add the hacktoberfest topic, so it will count towards your progress! 🎉
So, what do you think of this new plugin?
Posted on October 16, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.