Skip to content

Instantly share code, notes, and snippets.

@danielpost
Created August 11, 2020 20:39
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save danielpost/20130acf3e7594fb3205ffe98c42aff4 to your computer and use it in GitHub Desktop.
Save danielpost/20130acf3e7594fb3205ffe98c42aff4 to your computer and use it in GitHub Desktop.
Eleventy: Purge CSS for each html file
const { PurgeCSS } = require('purgecss');
/**
* Remove any CSS not used on the page and inline the remaining CSS in the
* <head>.
*
* @see {@link https://github.com/FullHuman/purgecss}
*/
eleventyConfig.addTransform('purge-and-inline-css', async (content, outputPath) => {
if (process.env.ELEVENTY_ENV !== 'production' || !outputPath.endsWith('.html')) {
return content;
}
const purgeCSSResults = await new PurgeCSS().purge({
content: [{ raw: content }],
css: ['dist/css/style.css'],
keyframes: true,
});
return content.replace('<!-- INLINE CSS-->', '<style>' + purgeCSSResults[0].css + '</style>');
});
{% if site.environment === 'production' %}
<!-- INLINE CSS-->
{% else %}
<link rel="stylesheet" href="/css/style.css">
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment