To start with we need to install CSS purge and Glob.
At the top of your Laravel webpack.mix.js file you need to include Purge CSS and Glob.
We want the plugin to run just during our production process, therefore we can use the mix function
inProduction to check the environment. Then we add the CSS Purge plugin to search in the resources folder for blade templates or Vue templates for what CSS classes or IDs are used.
When we run
npm run dev webpack will now build our asset files in development mode which will not use CSS purge. This is the result of the build.
/js/app.js 1.65 MB /css/app.css 246 kB
When we run
npm run prod it will minify the JS and CSS files to get them as small as possible. This will already reduce the file size enough for a production environment. This command will reduce the file css to the following.
/js/app.js 186 kB /css/app.css 179 kB
Now if we turn on purge CSS and re-run
npm run prod we're now left with the following file sizes.
/js/app.js 186 kb css/app.css 7.9 kB
As you can see the CSS file has gone from 179kb to 7.9kb, that's a HUGE 183% saving from an already compressed file, simply by searching for what CSS classes are actually used. ## Spatie PurgeCSS Package
Spatie have released a Laravel package that will add the above functionality into your application with zero config setup. All you have to do is include the package into your application and add the webpack function and that's it. Laravel Mix PurgeCSS First install it using npm.
npm install laravel-mix-purgecss
Then require it into your webpack config like below.
let mix = require('laravel-mix'); require('laravel-mix-purgecss'); // ... mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css') .purgeCss();
Get weekly updates to your email