Remove unused styles and minify CSS for Jekyll
John Otander wrote a post in June 2015 about
using UnCSS to remove unused CSSfrom Jekyll projects
. In his post he shows us how to do this
using Node.js and a build.js
script. His example script works perfectly,
but I was annoyed by the fact that the final stylesheet was not minified
(compressed), even when the source stylesheet was1.
I did some research and ended up with a modified build.js
script that, in
addition to removing unused styles, also minifies the result. The latter is
done with
clean-css
, a CSS minifier for Node.js.
Start with installing the clean-css
package:
npm i --save clean-css
After the install is successfull, replace the original build.js
script
with my modified version:
var uncss = require('uncss')
var cleancss = require('clean-css')
var glob = require('glob')
var fs = require('fs')
var stylesheetLocation = '_site/assets/css/'
var stylesheetSourceLocation = 'assets/css/'
var stylesheetName = 'main.css'
var stylesheetMinName = 'main.min.css'
var jekyllUncss = function() {
var css = fs.readFileSync(stylesheetLocation + stylesheetName, 'utf8')
glob('_site/**/*.html', function(err, files) {
if (err) {
console.log(err)
}
uncss(files, {
raw: css,
ignore: [/no-touch/],
ignoreSheets:[/\/css\//]
}, function(err, output) {
if (err) {
console.log(err)
}
new cleancss().minify(output, function(err, minified) {
if (err) {
console.log(err)
}
fs.writeFileSync(stylesheetSourceLocation + stylesheetMinName, minified.styles)
})
})
})
}
jekyllUncss()
What my modified script does differently than the original script2, is that
it runs the output from UnCSS, which basically is the original stylesheet with
unused styles removed, through clean-css before saving the new stylesheet as
main.min.css
. This results in a minified stylesheet with all unused
styles removed.
Using the example project from the original article, I managed to further decrease the file size down to 3.4 KB (3436 B). This is a 31 % decrease from the already optimized file. Not bad!
-
Jekyll offers out of the box support for minifying Sass stylesheets by using the
style
option in_config.yml
. More information can be found in the Jekyll documentation . ↩︎ -
A comparison of the original script and my modified script is available here . ↩︎