DEV Community

Saul Hardman
Saul Hardman

Posted on • Originally published at viewsource.io on

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"]
            }
          ]
        }
      }
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)