metalsmith-remove-unused-css v1.0.1
metalsmith-remove-unused-css
A metalsmith plugin for removing unused CSS.
This plugin removes unused CSS from the HTML document and CSS code by checking if the selectors in the CSS code exist in any of the HTML files in the Metalsmith files. Under the hood metalsmith-remove-unused-css
uses jsdom
and css-tree
parse out all of the selectors in the CSS files and <style>
tags, checks if any element in the HTML files matches those selectors, and if not removes those selectors from the CSS source files. The mechanism used for CSS dead code elimination in this plugin is similar to that of the uncss
library.
Installation
npm install metalsmith-remove-unused-css
Usage
To use this plugin, simply add it to the existing plugins in your Metalsmith source file or include it in the Metalsmith JSON file:
JavaScript
const Metalsmith = require('metalsmith');
const removeUnusedCss = require('metalsmith-remove-unused-css');
Metalsmith(__dirname)
.use(removeUnusedCss())
.build((err, files) => {
if (err) { throw err; }
});
JSON
{
"plugins": {
"metalsmith-remove-unused-css": {}
}
}
Options
You can pass options to metalsmith-remove-unused-css
with the Javascript API or CLI. The options are:
- htmlPattern: optional. Only HTML files that match this pattern will be processed. Accepts a string or an array of strings. The default is
**/*.html
. - cssPattern: optional. Only CSS source files that match this pattern will be processed. Accepts a string or an array of strings. The default is
**/*.css
.
htmlPattern
Only HTML files that match this pattern will have unused CSS removed, and will be checked for the existence of selectors. So this Metalsmith JavaScript configuration or metalsmith.json
:
JavaScript
const Metalsmith = require('metalsmith');
const removeUnusedCss = require('metalsmith-remove-unused-css');
Metalsmith(__dirname)
.use(removeUnusedCss({
htmlPattern: 'blog/**/*.html',
}))
.build((err, files) => {
if (err) { throw err; }
});
JSON
{
"source": "src",
"destination": "build",
"plugins": {
"metalsmith-remove-unused-css": {
"htmlPattern": "blog/**/*.html"
}
}
}
Would only process HTML files within the ./src/blog
folder, because the pattern
is relative to your source folder. See multimatch
for further details.
cssPattern
Only CSS files that match this pattern will have unused CSS removed. So this Metalsmith JavaScript configuration or metalsmith.json
:
JavaScript
const Metalsmith = require('metalsmith');
const removeUnusedCss = require('metalsmith-remove-unused-css');
Metalsmith(__dirname)
.use(removeUnusedCss({
cssPattern: 'blog/**/*.css',
}))
.build((err, files) => {
if (err) { throw err; }
});
JSON
{
"source": "src",
"destination": "build",
"plugins": {
"metalsmith-remove-unused-css": {
"cssPattern": "blog/**/*.css"
}
}
}
Would only process CSS files within the ./src/blog
folder, because the pattern
is relative to your source folder. See multimatch
for further details.