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: class {
                static extract(content) {
                  return content
                    .replace(/<style[\s\S]*>[\s\S]*<\/style>/gi, '')
                    .match(/[A-z0-9-:\\/]+/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.