Adding Prettier in Eleventy using Transforms

Posted on:

Recently I decided to look into some functionality in Eleventy I hadn't used before: Transforms. According to their website:

Transforms can modify a template’s output. For example, use a transform to format/prettify an HTML file with proper whitespace.

So let's try and use this functionality to have nicely formatted HTML by using Prettier. Prettier is a code formatter that can be used for a variety of languages and is customizable to your own preferences.

Added Prettier to the Eleventy config

Before using Prettier in Eleventy it needs to be installed. It's pretty (no pun intended) self-explanatory when visiting their docs: https://prettier.io/docs/install/. After installing you'll be able to use it in your Eleventy project. Go to your Eleventy config file and add the require statement for Prettier:

const prettier = require("prettier"); 

Next up, add the transform to the module.exports as follows:

eleventyConfig.addTransform("prettier", function (content) {
if ((this.page.outputPath || "").endsWith(".html")) {

let prettified = prettier.format(content, {
bracketSameLine: true,
printWidth: 512,
parser: "html",
tabWidth: 2
});
return prettified;
}

// If not an HTML output, return content as-is
return content;
});

This code will add the prettier transform, which handles all the content. It checks if the output path ends with .html, because we only want to format the HTML pages. If it's a HTML page, format the content of the page with whatever Prettier settings you prefer and return the pretty content. For all other content, don't do anything and return it as-is.

The settings I use are:

That's all there is to it. Running your Eleventy build will now have ✨pretty✨ HTML pages!

Likes, reposts and/or replies

Back to homepage