11ty transforms Markdown to HTML by template, not minimizes HTML. We have to use HTMLMinifier to optimize the HTML page.
Version
11ty 0.12.1
HTMLMinifier 4.0.0
Create Folder
$ mkdir 11ty-htmlminifier
Create a folder for the 11ty project.
Add HTMLMinifier
$ yarn init -y
$ yarn add @11ty/eleventy html-minifier --dev
Use Yarn to add related packages :
@11ty/eleventy
: for 11tyhtml-minifier
: minimize HTML under production mode
11ty Config
.eleventy.js
let htmlMinifier = require ('html-minifier')
module.exports = config => {
config.addTransform ('htmlMinifier', content => {
if (process.env.NODE_ENV === 'production') {
return htmlMinifier.minify (content, {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true,
})
}
return content
})
return {
htmlTemplateEngine: 'njk',
dir: {
input: 'src',
output: 'dist',
includes: 'template',
}
}
}
Line 4
config.addTransform ('htmlMinifier', content => {
if (process.env.NODE_ENV === 'production') {
return htmlMinifier.minify (content, {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true,
})
}
return content
})
config.addTransform
: modify the template’s output- Call HTMLMinifier to optimize HTML page under production mode
Line 15
return {
htmlTemplateEngine: 'njk',
dir: {
input: 'src',
output: 'dist',
includes: 'template',
}
}
Define 11ty setting :
htmlTemplateEngine
: use Numjucks as the default template enginedir
: user-defined directoryinput
: define markdown directoryoutput
: define build directoryincludes
: define template directory underinput
directory
Template
src/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello 11ty</title>
</head>
<body>
<div>Hello HTMLMinifier</div>
</body>
</html>
Normal HTML page.
NPM Config
package.json
{
"name": "11ty-lab",
"version": "1.0.0",
"scripts": {
"dev": "eleventy --serve",
"build": "NODE_ENV=production eleventy"
},
"devDependencies": {
"@11ty/eleventy": "^0.12.1",
"html-minifier": "^4.0.0"
}
}
Line 5
"dev": "eleventy --serve",
Run web server under development mode.
Line 6
"build": "NODE_ENV=production eleventy"
Set NODE_ENV=production
to optimize HTML under production mode.
Development Mode
$ yarn dev
Start web server under development mode.
11ty runs successfully under development mode.
HTML is not optimized under development mode.
Production Mode
$ yarn build
$ serve dist
Build HTML/CSS/JavaScript under production mode.
11ty runs successfully under production mode.
HTML is optimized under production mode.
Conclusion
- Using HTMLMinifier on
config.addTransform
optimizes HTML under production mode