Purgecss: Cannot be used correctly on ant-design

Created on 24 Feb 2019  路  16Comments  路  Source: FullHuman/purgecss

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.

Most helpful comment

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

All 16 comments

@Lizhooh You need to tell the plugin that ant exists.

You can either whitelist the ant classes, or include the paths to the components your using

I'm trying to think about a more viable solution to this issue, here: https://github.com/FullHuman/purgecss-webpack-plugin/issues/25#issuecomment-487082640

@OwenMelbz Any update on this? Owen when you mention including paths to the components do you mean import Button from 'antd/button'. @Telokis did you end up arriving at any alternative solutions?

@Jordan-Gilliam No, I ended up putting that aside while waiting for an answer, sadly

I was able to do was the following:

  1. Open any dynamic views using antd in chrome devtools. Copy all the html and past it in ant.html.
  2. Run ack 'class="*ant.*?">' ./public/ ant.html -o >> ant-classes.txt after building
  3. 3.
const fs = require('fs');

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
}
const antClasses = fs
    .readFileSync('./ant-classes.txt', 'utf-8')
    .split('class=')
  .flatMap(x => (x.match(/.*?>/) || [''])[0].replace(/"|>|'/g, '').split(' ')).filter(onlyUnique).slice(1);

fs.writeFileSync('./ant-classes.json', JSON.stringify(antClasses));
  1. Then add the class to white list.

Might take some additional tweaking

@Lizhooh have you fix it yet?

Any updates on this?

@hqman No progress, no fix

Would you mind setting up a repo to reproduce the issue? It will make it easier to look into it.

@Ffloriel hi, the reproduction example is here: https://github.com/Lizhooh/myapp-purgecss-demo

I faced the same issue. Will this be fixed soon ?

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

I faced the same issue. Will this be fixed soon ?

me too

I added my solution to this issue in the documentation. Feel free to share other solutions or issues with this solution if you found some.

I'm using an older version of Ant Design (3.x). Should this solution also work for this version?

Apparently the regex for the extractor seems not catching all class names properly specially if you want to keep the antd entirely, I have to remove the custom extractor to make it work

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eldiegod picture eldiegod  路  4Comments

claudiodekker picture claudiodekker  路  4Comments

JounQin picture JounQin  路  8Comments

TylerBarnes picture TylerBarnes  路  5Comments

simplenotezy picture simplenotezy  路  3Comments