Written by

Roberto Segura

Category:

Blog

14 October 2019

Today I tried to integrate Purgecss with Symfony through Webpack Encore and it was quite easy thanks to the guidance of Javier Eguiluz guidance in this Github Issue.

PurgeCSS removes any code style defined in your CSS files but not actually used in your site. That may be a lot depending on the size of your project.

 

First we need to add required dependencies for our integration:

npm install purgecss-webpack-plugin glob-all path --save-dev

 

Then add on top of your webpack.config.js required libraries definitions:

let Encore = require('@symfony/webpack-encore');
const PurgeCssPlugin = require('purgecss-webpack-plugin');
const glob = require('glob-all');
const path = require('path');

 

And finally add this in the bottom part of the webpack.config.js:

.addPlugin(new PurgeCssPlugin({
paths: glob.sync([
path.join(__dirname, 'templates/**/*.html.twig')
]),
content: ["**/*.twig"],
defaultExtractor: (content) => {
return content.match(/[\w-/:]+(?<!:)/g) || [];
}
}))

 

This searches for classes used in our twig templates stored in templates/**/*.html.twig.

If you are using vue (which was the case of the project I'm working in) you can add the components folder as a source to search for used classes:

.addPlugin(new PurgeCssPlugin({
paths: glob.sync([
path.join(__dirname, 'templates/**/*.html.twig'),
path.join(__dirname, 'assets/js/vue/**/*.vue'),
]),
  content: ["**/*.twig", "**/*.vue"],
defaultExtractor: (content) => {
return content.match(/[\w-/:]+(?<!:)/g) || [];
}
}))