2

我正在尝试将 webpack style-loader nonce 属性添加到craco 配置文件中,用于 create-react-app,如下所示:

// craco.config.js
module.exports = {
  webpack: {
    module: {
      rules: [
        {
          test: /\.css$/i,
          use: [
            {
              loader: "style-loader",
              options: {
                attributes: {
                  nonce: "12345678",
                },
              },
            },
            "css-loader",
          ],
        },
      ],
    },
  },
};

但这没有用。有没有人可以用craco实现这一点以及如何实现?

4

1 回答 1

5

问题

craco不让您module.rules直接以这种方式进行修改。

解决方案

相反,它为您提供webpack.configure了采用以下签名的方法:

configure: (webpackConfig, { env, paths }) => { return webpackConfig; }

为了覆盖style-loader(仅支持development模式),您需要一些辅助函数。这是给你的想法:

// Import these helpers to figure out where the current loader located
const { getLoader, loaderByName } = require("@craco/craco");

module.exports = {
  webpack: {
    configure: (webpackConfig, { env, paths }) => { 
      
      if (env === 'development') {
        // your overridden `style-loader`
        const overrideOptions = {
          loader: "style-loader",
          options: {
            attributes: {
              nonce: "12345678",
            },
          },
        };

        // override `style-loader`
        const { isFound, match } = getLoader(webpackConfig, loaderByName('style-loader'));

        if (isFound) {
          match.parent[match.index] = overrideOptions;
        }
      }

      return webpackConfig; 
    },
  },
};

于 2020-12-07T10:34:57.470 回答