Home

How to purge unused CSS

To exploit the full potential of Functional CSS, you must purge unused CSS. Purging unused CSS is the process of removing unused CSS from your application.

This process is essential because it reduces the size of your CSS files, which in turn reduces the size of your application. This process is especially important for Functional CSS because it is a utility-based approach, this means that it provides a a full set of utility classes that you can use to style your application. However, you will not use all of these classes in your application. Therefore, you must remove the unused classes from your CSS files.

Let's purge your CSS

First, let's go to Purge CSS website and read the instructions. Then, on your React or Next.js project, install the following packages:

$ npm install -D @fullhuman/postcss-purgecss postcss-cli

Then, create a postcss.config.js file in the root of your project and add the following code:

module.exports = {
  plugins: [
    process.env.NODE_ENV === "production" &&
      require("@fullhuman/postcss-purgecss")({
        content: ["./src/**/*.ts", "./src/**/*.tsx"],
        css: ["./src/**/*.css"],
        extractors: [
          {
            extractor: (content) => {
              return content.match(/[w-/:]+(?<!:)/g) || [];
            },
            extensions: ["js", "jsx", "ts", "tsx"],
          },
          {
            extractor: (content) => {
              return content.match(/[A-Za-z0-9-_]/g) || [];
            },
          },
        ],
        defaultExtractor: (content) => content.match(/[A-Za-z0-9-_]+/g) || [],
      }),
  ],
};

Once you have done this, you can run the build command to build your application. This will remove all unused CSS from your CSS files.

Results

This is the size of the CSS file before purging:

➜  my-project git:(master)yarn build
yarn run v1.22.19
warning ../package.json: No license field
$ tsc && vite build
vite v4.4.3 building for production...
355 modules transformed.
dist/index.html                   4.91 kB │ gzip:   3.23 kB
dist/assets/index-68360dbd.css   73.53 kB │ gzip:  10.97 kB
dist/assets/index-d487f6ea.js   417.47 kB │ gzip: 135.83 kB
✓ built in 1.42s
✨  Done in 3.81s.

Now, this is the size of the CSS file after purging:

➜  my-project git:(master)yarn build
yarn run v1.22.19
$ tsc && vite build
vite v4.4.8 building for production...
355 modules transformed.
dist/index.html                   4.94 kB │ gzip:   3.24 kB
dist/assets/index-d51e3b68.css    5.62 kB │ gzip:   1.71 kB
dist/assets/index-fd725c76.js   417.47 kB │ gzip: 135.82 kB
✓ built in 8.30s
Done in 13.71s.

As you can see, the size of the CSS file has been reduced from 73.53 kB to 5.62 kB. This is a huge size of reduction. This will make your application load faster. It's a 92.37% reduction, and the gzipped it's 84.38%