purgecss icon indicating copy to clipboard operation
purgecss copied to clipboard

Cannot be used correctly on ant-design

Open Lizhooh opened this issue 7 years ago • 19 comments

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.

Lizhooh avatar Feb 24 '19 03:02 Lizhooh

@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

OwenMelbz avatar Mar 28 '19 15:03 OwenMelbz

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

Telokis avatar Apr 26 '19 14:04 Telokis

@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 avatar Jul 22 '19 17:07 Jordan-Gilliam

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

Telokis avatar Jul 22 '19 18:07 Telokis

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
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

ghost avatar Jul 25 '19 18:07 ghost

@Lizhooh have you fix it yet?

hqman avatar Dec 17 '19 02:12 hqman

Any updates on this?

protortyp avatar Apr 11 '20 15:04 protortyp

@hqman No progress, no fix

Lizhooh avatar Apr 15 '20 14:04 Lizhooh

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

Ffloriel avatar Apr 20 '20 22:04 Ffloriel

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

Lizhooh avatar May 24 '20 10:05 Lizhooh

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

revskill10 avatar Jun 01 '20 10:06 revskill10

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

Ffloriel avatar Jun 01 '20 19:06 Ffloriel

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

me too

hqman avatar Jun 03 '20 03:06 hqman

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.

Ffloriel avatar Jun 13 '20 14:06 Ffloriel

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

stijnwesterhof avatar Jul 09 '20 08:07 stijnwesterhof

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

davidkhierl avatar Nov 23 '20 17:11 davidkhierl

I think the provided RegExpr in match doesn't work anymore because ant uses classes like .ant-col-24 {} or .ant-col-push-24 {}. This regular expression worked for me:

/([a-zA-Z-0-9-]+)(?= {)/g

So in extractor, instead of:

extractor: (content) => content.match(/([a-zA-Z-]+)(?= {)/g) || []

You need to use:

extractor: (content) => content.match(/([a-zA-Z-0-9-]+)(?= {)/g) || []

shkumbin avatar Jun 26 '21 16:06 shkumbin

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

joeyorlando avatar Feb 19 '22 01:02 joeyorlando

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

Jplus2 avatar Apr 13 '22 01:04 Jplus2