loading...
Cover image for Purging TailwindCSS without ejecting Create-React-App

Purging TailwindCSS without ejecting Create-React-App

jmhungdev profile image Jimmy ・2 min read

What's Purging: Purging is a term for eliminating unused css code. It decreases css file size in production to help browser load files faster. You may hear the term, tree shaking , normally used in the context of eliminating unused libraries to decrease js bundle size. Purge is the same concept.

There's an official doc to configure purge feature, but it doesn't go into the setup in the create-react-app environment. So if you want a step by step guide on using purge feature without ejecting your create-react-app, keep reading:

TailwindCSS 1.4.0+ has added PurgeCSS natively, users can now directly configure tailwind.config.js to eliminate unused css code in production.

  • First, you need to create a tailwind.config.js file.
  • Second, add all the js or jsx files that contains Tailwindcss classes under content property.
  • You also have the option to add "whitelist" for a list of class Names to not be purged
module.exports = {
  purge: {
    content: [
      './src/*.js',
      './src/*.jsx'
    ],
    options: {
      whitelist: ['bg-color-500']
    }
  },
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],

}

Once the config file is done, we need to run the build.

The only way to trigger purge is by setting NODE_ENV=production.
You can either export NODE_ENV=production in the console first or you can add it as a prefix before run script in package.json,

  "scripts": {
  "build:tailwind": "tailwindcss build src/index.css -o src/tailwind.css",
    "prestart":"npm run build:tailwind",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "prod:build": "NODE_ENV=production npm run build:tailwind react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject
  },

When you run npm run prod:build

  1. first it will set production as NODE_ENV variable
  2. run build:tailwind which then will trigger purge feature
  3. and build your React app with the purged version of tailwind.css

Make sure in your index.js, you are referencing the compiled Tailwind css file instead of index.css.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './tailwind.css';
import * as serviceWorker from './serviceWorker';

For more questions DM me on Twitter @jmhungdev

Posted on by:

Discussion

markdown guide
 

Another approach is to use RunCSS instead of TailwindCSS.

RunCSS is a runtime version of TailwindCSS. So by using RunCSS there is no need to purge CSS. See here: dev.to/mudgen/runcss-a-runtime-ver...