purgecss: Cannot be used correctly on ant-design

Cannot be used correctly on ant-design. Will delete the associated style.

Describe the bug

before use:

qq 20190224105316

after use:

qq 20190224105450

code:

import 'antd/dist/antd.min.css';
import { Button } from 'antd';
...
<p>
    <Button type='danger'>buy</Button>
</p>

config: ( use react-app-rewired on create-react-app )

const PurgecssPlugin = require('purgecss-webpack-plugin');
const glob = require('glob-all');

module.exports = function override(config, env) {
    const purgecssPlugin = new PurgecssPlugin({
        paths: ['./public/index.html', ...glob.sync(`./src/*`)],
    });

    if (env !== 'development') {
        config.plugins = [...config.plugins, purgecssPlugin];
    }

    return config;
};

To Reproduce Steps to reproduce the behavior:

  1. Go to ‘…’
  2. Click on ‘…’
  3. Scroll down to ‘…’
  4. See error

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. Windows]
  • Version of Purgecss [latest]
    "glob-all": "^3.1.0",
    "purgecss-webpack-plugin": "^1.4.0",

Additional context Add any other context about the problem here.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 6
  • Comments: 19 (3 by maintainers)

Commits related to this issue

Most upvoted comments

I wonder what this would look like for a Next.js project 🤔

Thanks a lot for the repo @Lizhooh , helped a lot.

This is what I came up with to make it work with ant-design, it is not an ideal solution but it should work.

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"],
    },
  ],

Any example of doing this manually on a manually configured webpack setup? (Not using CRA)