DEV Community

Cover image for How to minify your Eleventy build
Benjamin Rancourt
Benjamin Rancourt

Posted on • Originally published at benjaminrancourt.ca on

How to minify your Eleventy build

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:

const htmlmin = require("html-minifier");

module.exports = (eleventyConfig) => {
  eleventyConfig.addTransform("htmlmin", (content, outputPath) => {
    if (outputPath.endsWith(".html")) {
      return htmlmin.minify(content, {
        collapseWhitespace: true,
        removeComments: true,  
        useShortDoctype: true,
      });
    }

    return content;
  });
};
Enter fullscreen mode Exit fullscreen mode
Transforms Example: Minify HTML Output, on Eleventy

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
Enter fullscreen mode Exit fullscreen mode

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);
};
Enter fullscreen mode Exit fullscreen mode

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?

Top comments (0)