PurgeCSSPurgeCSS
API Reference
GitHub
API Reference
GitHub
  • PurgeCSS

    • About PurgeCSS
    • Getting Started
    • Configuration
    • Command Line Interface
    • Programmatic API
    • Safelisting
    • Extractors
  • Plugins

    • PostCSS
    • Webpack
    • Gulp
    • Grunt
    • Gatsby
  • Guides

    • Vue
    • React
    • Next.js
    • Nuxt.js
    • Razzle
    • WordPress
    • Hugo
  • Comparison
  • Common Questions

    • How to use with CSS modules
    • How to use with Ant Design

React

React is a JavaScript library for building user interfaces. Create React App is a comfortable environment for learning React, and is the best way to start building a new single-page application in React.

This guide assumes you are using create-react-app to build your single-page react application.

Method 1: Use craco

Custom PostCSS plugins (including PurgeCSS) can be added to Create React App apps using craco. Follow the craco installation instructions, then install the PurgeCSS PostCSS plugin and add it to the craco config:

npm i --save-dev @fullhuman/postcss-purgecss
// craco.config.js
const purgecss = require("@fullhuman/postcss-purgecss");

module.exports = {
  style: {
    postcss: {
      plugins: [
        purgecss({
          content: ["./src/**/*.html", "./src/**/*.tsx", "./src/**/*.ts"],
        }),
      ],
    },
  },
};

Method 2: Run PurgeCSS CLI in postbuild

Add the following code in package.json

"scripts": {
  "postbuild": "purgecss --css build/static/css/*.css --content build/index.html build/static/js/*.js --output build/static/css"
},

Method 3: eject create-react-app

You need to eject in order to expose the webpack configuration offered by original create-react-app

Install the webpack plugin for PurgeCSS:

npm i --save-dev glob-all purgecss-webpack-plugin

Now, modify the file config/webpack.prod.conf.js by adding the following code with the rest of the imports:

// import PurgeCSS webpack plugin and glob-all
const { PurgecssPlugin } = require("purgecss-webpack-plugin");
const glob = require("glob-all");

...and directly before new ManifestPlugin(...) in the plugins list, add this:

    // Remove unused css with PurgeCSS. See https://github.com/FullHuman/purgecss
    // for more information about PurgeCSS.
    // Specify the path of the html files and source files
    new PurgecssPlugin({
      paths: [paths.appHtml, ...glob.sync(`${paths.appSrc}/**/*`, { nodir: true })]
    }),
Edit this page
Last Updated:
Contributors: Floriel, John Bachir, Ffloriel, Peter Holcomb, charlie, David San
Prev
Vue
Next
Next.js