Transforms
Transforms can modify a template’s output. For example, use a transform to format/prettify an HTML file with proper whitespace.
INFO:
The provided transform function must return the original or transformed content.
Filename .eleventy.js
module.exports = function (eleventyConfig) {
// Can be sync or async
eleventyConfig.addTransform("transform-name", async function (content) {
console.log(this.page.inputPath);
console.log(this.page.outputPath);
return content; // no changes made.
});
};
Access to Eleventy’s page
variable (via this.page
) was added in Eleventy v2.0. For previous versions, consult the older versions of the docs.
Order of Execution Jump to heading
Transforms are executed in order of insertion in your configuration file.
eleventyConfig.addTransform("first", () => {});
eleventyConfig.addTransform("second", () => {});
eleventyConfig.addTransform("third", () => {});
Plugins Jump to heading
Transforms added via plugins are inserted via the second configuration stage for plugins.
eleventyConfig.addPlugin(eleventyConfig => {
eleventyConfig.addTransform("third", () => {});
});
eleventyConfig.addTransform("first", () => {});
eleventyConfig.addTransform("second", () => {});
Examples Jump to heading
Minify HTML Output Jump to heading
Filename .eleventy.js
const htmlmin = require("html-minifier");
module.exports = function (eleventyConfig) {
eleventyConfig.addTransform("htmlmin", function (content) {
if ((this.page.outputPath || "").endsWith(".html")) {
let minified = htmlmin.minify(content, {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true,
});
return minified;
}
// If not an HTML output, return content as-is
return content;
});
};