为什么purgeCSS会删除我React-Bootstrap应用程序中使用的样式?

9

我正在尝试清除应用程序中未使用的样式。但是当清除时,它仍会删除已使用的类,导致网站看起来损坏。

我正在使用以下软件包:

  "dependencies": {
    "@fullhuman/postcss-purgecss": "^4.0.3",
    "autoprefixer": "^10.3.4",
    "bootstrap": "^5.1.1",
    "next": "^11.1.0",
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-preset-env": "^6.7.0",
    "react": "17.0.2",
    "react-bootstrap": "^1.6.3",
    "react-dom": "17.0.2",
    "sass": "^1.40.1"
  }

./styles文件夹中,我有一个layout.scss文件,在其中我还导入了@import "../node_modules/bootstrap/scss/bootstrap";。然后在_app.js中导入了import "../styles/layout.scss";
我创建了一个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: [
          "./pages/**/*.{js,jsx,ts,tsx}",
          "./components/**/*.{js,jsx,ts,tsx}",
          "./node_modules/react-bootstrap/**/*.js",
        ],
        defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
        safelist: ["html", "body"],
      },
    ],
  ],
};

我在之前的帖子中建议的方法中,包括了"./node_modules/react-bootstrap/**/*.js",这确实有一定帮助,但仍然会移除react-bootstrap使用的类。

我还尝试在postcss.config.js中添加css: ["./styles/**/*.scss, ./styles/**/*.css"],但似乎也没有作用。

即便如此,它仍然看起来有问题:

enter image description here

而它应该是这样的:

enter image description here


这里有一个评论说purgeCSS不能与react-bootstrap一起使用,我们需要显式地设置classNames。 - TigerCode
还有一个论坛 https://giters.com/FullHuman/purgecss/issues/491,其中详细讨论了这个问题,并提供了可能的解决方案。 - TigerCode
@TigerCode,我没有任何进展,因为我已经转向了MUI(Material UI)。你最新的链接确实承诺了一个解决方案,虽然不是完美的,但至少有点帮助。我可能会在接下来的一周测试它。 - Mark
1个回答

2

在'@fullhuman/postcss-purgecss'插件中的这个配置属性保留了我的Bootstrap模态框,所以我猜你需要将所需保留的确切Bootstrap组件中使用的CSS前缀添加到白名单中,以避免被清除。

safelist: {
            standard: ['html', 'body', 'btn'],
            deep: [/^col/, /^navbar/, /^nav/, , /^modal/]
          },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接