简体   繁体   中英

How can I purge CSS based on the HTML output?

I'm currently working on a project in Next.js where we use custom SCSS combined with Bootstrap SCSS and React-Bootstrap. We noticed our main.scss file (where our custom SCSS and Bootstrap SCSS is bundled) is getting too heavy.

When I checked in the coverage tab in Chrome, I noticed 95% of the CSS is not being used. So I want to get rid of all the CSS which is in the Bootstrap SCSS files and which is not being used.

I found that you can purge CSS by adding a postcss.config.js file in Next.js and then adding purgeCSS there ( https://purgecss.com/guides/next.html ).

The problem is that this is based on the source code (JS,JSX,TS,TSX files). In the source file we use react-bootstrap components, which use some of the CSS in the Bootstrap SCSS files too. This is not picked up by purgeCSS because the classes are not literally in the source code.

This is why I want the purgeCSS to run on the output HTML from Next.js. For this I adapted the build task in my package.json to this:

"build": "next build && purgecss --css ./.next/static/**/*.css  --content ./.next/server/**/*.html --output ./.next/static/css",

This works fine, the CSS output is exactly what I want. But I don't know how to make it so Next.js actually uses this new CSS file on the website instead of the unoptimized CSS. Any ideas?

If you use regex with the safelist attribute in your postcss.config.js file, then purgecss will work correctly. We had the same problem with bootstrap-react, purgecss, and next.js. Here's our postcss.config.js:

module.exports = {
plugins: [
    
  "postcss-flexbugs-fixes",
  [
    "postcss-preset-env",
    {
      autoprefixer: { flexbox: "no-2009" },
      stage: 3,
      features: { "custom-properties": false }
    }
  ],
  [
    "@fullhuman/postcss-purgecss",
    {
      content: ['./components/**/*.{js,jsx,ts,tsx}', "./pages/**/*.{js,jsx,ts,tsx}"],
      css: ['./styles/**/*.{css,scss}'],
      defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
      safelist: {
          standard: ["html", "body", "btn" ], 
          deep: [/^col/, /^navbar/, /^nav/]
      }
    }
  ]
]};

Basically, I've added the regex expressions to safelist any classes that start with "col", "navbar", and "nav". Just inspect any of the classes that aren't getting picked up and add the corresponding regex expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM