Right-Click → View Page Source

Configuring PurgeCSS for Use With Nuxt

PurgeCSS is a tool for removing unused CSS. It achieves this by cross-checking the compiled CSS with a list of selectors that are extracted from the content files (e.g. HTML files, JavaScript modules, and Vue components).

Using PurgeCSS out of the box with Nuxt resulted in styles included via @import statements being correctly purged – both from 1st- and 3rd-party sources. However, due to the configuration of the default extractors, styles authored within Vue component <style> blocks were incorrectly preserved.

Configuring the PurgeCSS PostCSS plugin as follows remedies the problem:-

// nuxt.config.js
export default {
  build: {
    postcss: {
      plugins: {
        '@fullhuman/postcss-purgecss': {
          extractors: [
            {
              extractor: content =>
                content
                  .replace(/<style[\s\S]*>[\s\S]*<\/style>/gi, '')
                  .match(/[\w-/:]+/g) || [],

              extensions: ['vue'],
            },
          ],
        },
      },
    },
  },
};

Ideally this extraction behaviour would be consolidated within a tested and maintained package such as purge-from-vue. That way it could be used in all Vue-based projects.

UPDATE (2020-03-21): Reflect change to extractor format in PurgeCSS v2.0 release.

Join the converstation on the DEV Community or send a Webmention

About the author

A profile photo of Saul Hardman

Hiya, I'm Saul Hardman, a front-end engineer based in Copenhagen, Denmark. I'm currently available for work, so if you need help building websites, web applications, and everything in between get in touch!

To stay up to date, follow me on Twitter and GitHub and be sure to subscribe to the RSS feed.