3
votes

I am trying to remove unused css rules from one or more of my sass files.

Research led me to postcss-uncss as the best option for removing unused css if you do not use server-side rendering (see: https://www.purgecss.com/comparison)

https://github.com/uncss/postcss-uncss

Now, postcss-uncss is a wrapper for uncss: https://github.com/uncss/uncss However, the uncss documentation is confusing to me, and the example configuration here is not useful: https://github.com/uncss/postcss-uncss#example-configuration

How does one configure postcss-uncss for Laravel Mix?

THis is what I have so far:

mix.js('resources/js/app.js', 'public/js')
    .options({
        processCssUrls: false,
        postCss: [
            require('postcss-uncss'),
            tailwindcss('./tailwind.config.js')
        ],
    })

I want to:

  1. Tell it which laravel routes to use (or 'all' should also be fine)
  2. Where my sass / scss files are located: /resources/sass/* (example files: /resources/sass/app.scss, /resources/sass/admin/admin.scss, etc)
  3. Where to put the output ie the compiled (and cleaned up) css without the unused rules: /public/css/* (so as to preserve the same structure, for example: /public/app.css, /public/admin/admin.css, etc)

Thoughts would be greatly appreciated.

2

2 Answers

1
votes

This is what I ended up doing (used purgecss, which turns out, is a better option than uncss, according to my conversation with Adam Wathan

let mix = require('laravel-mix');

const tailwindcss = require('tailwindcss');

// Removes unused CSS
// According to Discord chat: Running Purge CSS as part of Post CSS is a ton faster than laravel-mix-purgecss
// But if that doesn't work use https://github.com/spatie/laravel-mix-purgecss
const purgecss = require('@fullhuman/postcss-purgecss')({
  // Specify the paths to all of the template files in your project 
  content: [
    './resources/views/*.php',
    './resources/views/**/*.php',
    './resources/js/components/*.vue',
    './resources/js/components/**/*.vue',
  ],

  // Include any special characters you're using in this regular expression
  defaultExtractor: content => content.match(/[A-Za-z0-9-_:/]+/g) || []
});

mix.options({
        clearConsole: true, // in watch mode, clears console after every build
        processCssUrls: false,
        postCss: [
            //require('tailwindcss'),
            tailwindcss('./tailwind.config.js'),

            // to enable purgecss on production only
            ...process.env.NODE_ENV === 'production' ? [purgecss] : []

            // to enable on all environments, local and production
            //purgecss
        ],
    })
   ;
0
votes

Perhaps you might try the Spatie package?

Let's install it.

npm i laravel-mix-purgecss

Call purgeCss() in your webpack.mix.js.

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .purgeCss({ enabled: true });