PurgeCSS中文文档网PurgeCSS中文文档网
首页
文档
API参考
GitHub
首页
文档
API参考
GitHub
  • PurgeCSS

    • 关于PurgeCSS
    • 快速开始
    • 配置
    • 命令行接口
    • 编程API
    • 安全列表
    • 提取器
  • 插件

    • PostCSS插件
    • Webpack插件
    • Gulp插件
    • Grunt插件
    • Gatsby插件
  • 指南

    • Vue
    • React
    • Next.js
    • Nuxt.js
    • Razzle
    • WordPress
    • Hugo
  • 比较
  • 常见问题

    • 如何与CSS模块一起使用
    • 如何与Ant Design一起使用

How to use with Ant Design

提示

The content of this page comes from this issue.

PurgeCSS works by comparing the selectors in your content files with the ones on your CSS files. When using component libraries with their own CSS, it happens the CSS is removed because the content is not found. You then need to specify where the content can be found.

In the case of ant-design, the list of selectors used in ant-design cannot be retrieve easily from its content.

Below is a way to use PurgeCSS with Ant Design and React. The project was created with create-react-app. Then, it is using react-app-rewired to extend the configuration.

const glob = require("glob-all");
const paths = require("react-scripts/config/paths");

const { override, addPostcssPlugins } = require("customize-cra");

const purgecss = require("@fullhuman/postcss-purgecss")({
  content: [
    paths.appHtml,
    ...glob.sync(`${paths.appSrc}/**/*.js`, { nodir: true }),
    ...glob.sync(`${paths.appNodeModules}/antd/es/button/**/*.css`, {
      nodir: true,
    }),
  ],
  extractors: [
    {
      extractor: (content) => content.match(/([a-zA-Z-]+)(?= {)/g) || [],
      extensions: ["css"],
    },
  ],
});

module.exports = override(
  addPostcssPlugins([
    ...(process.env.NODE_ENV === "production" ? [purgecss] : []),
  ])
);

I essentially added a path to the antd css file that I want to keep. in the example below, button.

...glob.sync(`${paths.appNodeModules}/antd/es/button/**/*.css`,

To keep antd entirely, you could replace by

...glob.sync(`${paths.appNodeModules}/antd/es/**/*.css`,

and wrote an extractor for css file that intend to get the selectors from the file:

  extractors: [
    {
      extractor: (content) => content.match(/([a-zA-Z-]+)(?= {)/g) || [],
      extensions: ["css"],
    },
  ],
Edit this page
Prev
如何与CSS模块一起使用