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

Saul Hardman is a contract front-end web developer based in Copenhagen, Denmark. During his career he's worked with the likes of The Guardian, UNIT9, and AllofUs. As of now he's helping Realla with front-end architecture, performance, and technical SEO.

To stay up to date, follow Saul on Twitter and GitHub or subscribe to the RSS feed.