- Stable
3.0.0
- Canary
3.0.1-alpha.5
Menu
Eleventy
5.81s
Gatsby
43.36s
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.
eleventy.config.js
export default 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.
});
};
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.
Running Transforms Manually
Jump to section titled: Running Transforms ManuallyAdded in v3.0.0 The renderTransforms
universal filter allows projects to run transforms manually on blocks of arbitrary HTML content.
Order of Execution
Jump to section titled: Order of ExecutionTransforms are executed in order of insertion in your configuration file.
eleventyConfig.addTransform("first", () => {});
eleventyConfig.addTransform("second", () => {});
eleventyConfig.addTransform("third", () => {});
Plugins
Jump to section titled: PluginsTransforms 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 section titled: ExamplesMinify HTML Output
Jump to section titled: Minify HTML Outputeleventy.config.js
import htmlmin from "html-minifier-terser";
export default 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;
});
};
const htmlmin = require("html-minifier-terser");
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;
});
};
Note that html-minifier-terser
has a significant number of options, most of which are disabled by default.