【问题标题】:How to add webpack style-loader nonce attribute to a craco config如何将 webpack 样式加载器随机数属性添加到 craco 配置
【发布时间】:2021-03-17 16:39:15
【问题描述】:

我正在尝试将 webpack style-loader nonce attribute 添加到 craco config file,用于 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 实现这一点以及如何实现?

【问题讨论】:

    标签: javascript webpack create-react-app craco


    【解决方案1】:

    问题

    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; 
        },
      },
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 2016-03-06
      • 2021-11-09
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      相关资源
      最近更新 更多