最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add webpack style-loader nonce attribute to a craco config - Stack Overflow

programmeradmin0浏览0评论

I'm trying to add the webpack style-loader nonce attribute to a craco config file, for a create-react-app, like this:

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

but that didn't work. Does anyone if this can be achieved with craco and how?.

I'm trying to add the webpack style-loader nonce attribute to a craco config file, for a create-react-app, like this:

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

but that didn't work. Does anyone if this can be achieved with craco and how?.

Share Improve this question asked Dec 6, 2020 at 1:05 Adrian GuerreroAdrian Guerrero 8101 gold badge9 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Problem

craco doesn't offer you to modify module.rules directly that way.

Solution

Instead it offers you webpack.configure method instead which takes following signature:

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

In order to override style-loader (only support development mode), you would need a few helper functions. Here is the idea for you:

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

发布评论

评论列表(0)

  1. 暂无评论