How to remove unused CSS codes?

With the continuous iteration of front-end projects, some CSS codes may not be used. These unused codes can affect application performance.

So, how to efficiently remove unused CSS code? This article will introduce a powerful tool - PurgeCSS, which can automatically detect and remove unused CSS code. Whether in Vue, React or other front-end frameworks, PurgeCSS can be easily integrated.

Next, let's explore how to configure and use PurgeCSS, and some advanced configuration options to help us customize the process of removing unused CSS code according to the needs of the project!

Table of contents

unused css

What is PurgeCSS?

How does PurgeCSS work?

Combined with JS library/framework

React + PurgeCSS

Vue + PurgeCSS

Advanced Configuration Options

keyframes 和 fontfaces

content and css

extractors

variables

safelist and comments

Related Links


unused css

Using the Coverage panel of the Chrome browser, you can see the usage of all CSS files on the current page (open the Coverage panel: Ctrl+Shift+P, search for Coverage):

This shows the total size of each file, the size of unused CSS, and the percentage of unused CSS. As you can see, most of the CSS is unused in the file.

Click to open a file, and you can see which styles are used (blue) and which styles are not used (red) in this file:

By default, the browser must download, parse, and process all external style sheets it encounters before it can render content to the user's screen. Every external style sheet must be downloaded from the network. These extra network tasks can significantly increase the amount of time the user has to wait before seeing anything on the screen.

Unused CSS also slows down the browser's ability to build the render tree. The render tree is similar to the DOM tree, except it also contains styles for each node. To build the render tree, the browser must walk the entire DOM tree and check which CSS rules apply to each node. The more unused CSS, the more time the browser may need to spend calculating styles for each node.

What is PurgeCSS?

PurgeCSS is a tool for removing unused CSS. It is often useful for optimizing applications. When using CSS frameworks like Bulma, Bootstrap or Tailwind, there is a lot of unused CSS. This is where PurgeCSS comes in. It analyzes content and CSS files to determine which styles are not used and removes them. PurgeCSS can be used with most common JavaScript libraries/frameworks such as Vue.js, React, Gatsby, etc.

While PurgeCSS isn't the only tool for removing unused CSS, it stands out for its modularity, ease of use, and extensive customization options. Modularity enables developers to create module extractors for specific use cases and frameworks. Extractors are functions that read the contents of a file and extract the list of CSS selectors used.

PurgeCSS provides a very solid default extractor that can handle a wide variety of file types. However, by default, PurgeCSS ignores unused CSS code that contains special characters like @, :, and /. Therefore, PurgeCSS may not be fully adapted to the file type or CSS framework you are using.

In addition, PurgeCSS has many configuration items, which can customize its behavior according to needs. For example, PurgeCSS includes options for fontFace, keyframes, extractors, CSS, and more. Customization can improve the performance and efficiency of PurgeCSS. PurgeCSS is easy to learn and has detailed documentation. As of this writing, PurgeCSS has over 900,000 weekly downloads on npm and 7.4k+ Stars on GitHub[1].

How does PurgeCSS work?

PurgeCSS is suitable for production use, it can analyze content and CSS and remove unused styles. It is not necessary to run PurgeCSS during development, because during development, unused styles may be created frequently, which means that PurgeCSS must be run every time.

Instead, it can be run against production builds only. This way, deleted styles don't have to be recreated. So, when the app is ready for production, you can run PurgeCSS once. Before we start using PurgeCSS with popular libraries/frameworks, let's take a look at how it works with plain JavaScript. code show as below:

(async () => {
  const purgecss = await new PurgeCSS().purge({
    content: ['index.html'],
    css: ['style.css'],
  });

  console.log(purgecss);
})();

Here index.html is specified as one of the contents, style.css is specified as one of the CSS, more contents and CSS files can be included, and the contents are not limited to HTML files. The code above returns an array with styles cleared.

In addition to content and css, there are many more configuration items to specify exactly what you want it to do and how to do it. The above example can be used for any normal JavaScript project. To use PurgeCSS, you need to have a separate JavaScript file that will run once to remove unused styles.

The cleared style can replace the current style with the following code:

const { PurgeCSS } = require('purgecss');
const fs = require('fs');

(async () => {
  const purgecss = await new PurgeCSS().purge({
    content: ['index.html'],
    css: ['style.css'],
  });

  fs.writeFileSync('style.css', purgecss[0].css);
})();

Combined with JS library/framework

PurgeCSS is compatible with popular JavaScript libraries/frameworks such as React, Vue, Gatsby, Next.js, Nuxt.js, etc. Let's see how to use PurgeCSS with React and Vue.

React + PurgeCSS

First you need to install PurgeCSS and its dependencies:

npm i --save-dev @fullhuman/postcss-purgecss

Open the App.js file and paste the following code:

import "./App.css";

function App() {
  return <div className="App"></div>;
}

export default App;

In the above code, we created a function component named App and returned a div with class name App. App.css remains unchanged, so it contains the following unused CSS code.

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

Open the package.json file and add the following code under script:

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

post is a prefix that can be added to any npm script and will be automatically run when the main script is run. In this example, postbuild runs after executing the build script. The command executed by postbuild contains three options.

  • --css option: Specifies the CSS files that PurgeCSS should process, it can be an array of filenames or a global variable.
  • --content option: Specifies what content PurgeCSS should analyze.
  • --output option: Specifies to which directory the purified CSS files should be written. By default it places the result in the console.

Essentially, the commands executed by postbuild do the following:

  1. Checks every CSS file in build/static/css.
  2. Matches selectors used in the file and removes any unused CSS.
  3. Output new CSS files in build/static/css.

Now, just run npm run build to run the build of the React app. To confirm success, open the CSS file in build/static/css. The output is similar to the code below, only including the CSS used:

body {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  margin: 0;
}
code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, Courier New, monospace;
}
.App {
  text-align: center;
}
@-webkit-keyframes App-logo-spin {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(1turn);
    transform: rotate(1turn);
  }
}
@keyframes App-logo-spin {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(1turn);
    transform: rotate(1turn);
  }
}

Vue + PurgeCSS

PurgeCSS can be installed in Vue by:

vue add @fullhuman/purgecss

This will generate a postcss.config.js file in which the PurgeCSS configuration suitable for Vue applications has been set. These configurations can be changed as needed.

Let's update some app content and see how PurgeCSS works in Vue. Go to HelloWorld.vue and replace the code in it with the following:

<template>
  <a href="#">Hello world</a>
</template>
<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
};
</script>

<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
span {
  color: red;
}
</style>

Here the content is reduced and some unused styles are added. Now, run npm run build in a terminal to build the app and see the final built CSS. Finally, by opening the CSS file in the dist/css directory, you can find the CSS output containing only the styles used:

a[data-v-70cf4e96] {
  color: #42b983;
}

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

Advanced Configuration Options

Only three configuration options were seen above: content, css and outline, let's see how to customize PurgeCSS through other configuration options.

keyframes 和 fontfaces

Prior to PurgeCSS v2.0, unused font and keyframe code was removed by default. However, when these functions are used incorrectly, the code breaks down. Unused font and keyframe codes are now left unchanged by default. This default behavior can be changed by setting the keyframes and fontfaces options to true:

(async () => {
  const purgecss = await new PurgeCSS().purge({
    content: ['index.html'],
    css: ['style.css'],
    keyframes: true,
    fontFaces: true,
  });

  console.log(purgecss);
})();

You can also modify these configuration items in the purgecss.config.js configuration file:

// purgecss.config.js
module.exports = {
  content: ['index.html'],
  css: ['style.css'],
  keyframes: true,
  fontFaces: true,
}


(async () => {
  const purgecss = await new PurgeCSS().purge('./purgecss.config.js');
  console.log(purgecss);
})();

content and css

You can pass in content and css values ​​directly without linking a file:

// purgecss.config.js
module.exports = {
  content: [
    {
      raw: '<html><body><p>Hello world</p></body></html>',
      extension: 'html',
    },
  ],
  css: [
    {
      raw: 'p { color: red }',
    },
  ],
};

extractors

In rare cases, PurgeCSS may fail to remove unused CSS or remove used CSS. In this case, a custom extractor must be used. PurgeCSS relies on extractors to get the list of selectors used in the file.

Some packages provide extractors for specific extensions. For example, purgecss-from-js is specific to the .js extension. Scaling with specific extractors gives the best accuracy:

// purgecss.config.js
import purgeJs from 'purgecss-from-js'
import purgeHtml from 'purgecss-from-html'

const options = {
  content: ['index.html'],
  css: ['style.css'],
  extractors: [
    {
      extractor: purgeJs,
      extensions: ['js']
    },
    {
      extractor: purgeHtml,
      extensions: ['html']
    }
  ]
}
export default options

variables

By default, unused CSS variables are not removed. If you want to remove them, you must specify the variable as true in the purgecss.config.js file:

module.exports = {
    content: ['index.html'],
    css: ['style.css'],
    variables: true,
}

safelist and comments

PurgeCSS supports specifying which selectors are safe to keep in the final CSS. This can be done in two ways: PurgeCSS's safelist option or special CSS-specific comments. Using safelists:

module.exports = {
    content: ['index.html'],
    css: ['style.css'],
    safelist: ['random', 'button'],
}

In this case, .random, #random, button, .button, and #button are all ignored and not removed by PurgeCSS. It supports the use of regular expressions:

module.exports = {
    content: ['index.html'],
    css: ['style.css'],
    safelist: [/red$/, /^bg/],
}

In this case, any selectors that end with red (eg, bg-red, btn-red) or begin with bg (eg, bg-blue, bg-red) are not removed. By default, PurgeCSS does not remove comments, only special comments designed to customize PurgeCSS behavior.

A common set of special annotations are used to specify which selectors are safe to keep in the final CSS:

/* purgecss start ignore */
h1 {
  color: pink;
  font-size: 2rem;
}
/* purgecss end ignore */

Related Links

[1]GitHub: https://github.com/FullHuman/purgecss。

Guess you like

Origin blog.csdn.net/wangonik_l/article/details/131897940