8

I'm trying to remove unused css from my NextJS project using PurgeCSS. However, I'm having difficulty getting the most basic integration of PurgeCSS into my project to work.

I'm using this documentation: https://www.purgecss.com/guides/next.

My next.config file looks like this:

// next.config.js
const withCss = require('@zeit/next-css')
const withPurgeCss = require('next-purgecss')

module.exports = withCss(withPurgeCss())

Here is my component:

import React from 'react'
import App from 'next/app'

export default class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props

    return (
      <>
        <style jsx global>{`
          .purgecss-test {
            color: red;
          }
        `}</style>
          <Component {...pageProps} />
      </>
    )
  }
}

When I do a global search in my code base for 'purgecss-test', I only get the one result that's in the component above, so I am expecting that style to be removed during the build. However, when my app builds and I navigate to the page and inspect the source, I can still see it there:

<style amp-custom="">.purgecss-test{color:red;}
1

1 Answer 1

7

Try customizing PostCSS instead as per this page (ignore tailwindcss): https://nextjs.org/learn/basics/assets-metadata-css/styling-tips

A bit simplified, install @fullhuman/postcss-purgecss and postcss-preset-env, then create a postcss.config.js file in the top-level directory and enter this in it:

module.exports = {
    plugins: [
        [
            '@fullhuman/postcss-purgecss',
            {
                content: [
                    './pages/**/*.{js,jsx,ts,tsx}',
                    './components/**/*.{js,jsx,ts,tsx}'
                ],
                defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
            }
        ],
        'postcss-preset-env'
    ]
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.