【问题标题】:How to remove a webpack module rule pre compilation?如何删除 webpack 模块规则预编译?
【发布时间】:2021-09-20 08:23:12
【问题描述】:

我正在使用 webpack 5,并正在使用 webpack-merge 库合并多个 webpack 配置,在一种情况下,我得到的结果有两个相互竞争的规则。换句话说,它们都测试相同的正则表达式,但加载器的详细信息不同。

第一个用于生产:

      {
        test: /\.(ts|js)x?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      },

第二个仅用于开发:

      {
        test: /\.(ts|js)x?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              plugins: [require.resolve('react-refresh/babel')]
            }
          }
        ]
      }

导致...

...
  module: {
    rules: [
      {
        test: /\.(ts|js)x?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      },
      {
        test: /\.(ts|js)x?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              plugins: [require.resolve('react-refresh/babel')]
            }
          }
        ]
      }
    ]
   }
...

我想做的是在编译期间(或预编译)删除其中一个。

我研究过使用 webpack 钩子,但没有成功。我不确定它们是否适合这项工作。

我还查看了webpack-chain 库,但对于我需要的东西来说,这似乎有点矫枉过正。另外,据我了解,这需要我将所有 webpack 配置重新重写为它的格式。

有没有一种简单的方法可以通过回调或其他方式修改配置?“

【问题讨论】:

    标签: webpack webpack-5


    【解决方案1】:

    我可以为此使用 webpack 钩子。这是我的解决方案:

    module.exports = class DevRefreshRuleUpdatePlugin {
      apply(compiler) {
        compiler.hooks.watchRun.tap('DevRefreshRuleUpdatePlugin', compiler => {
          const rules = compiler.options.module.rules.filter(rule => {
            if (!rule.test.toString().match(/\.\(ts\|js\)x\?\$/)) return rule;
          });
    
          const updatedRules = [
            {
              test: /\.(ts|js)x?$/,
              exclude: /node_modules/,
              use: [
                {
                  loader: 'babel-loader',
                  options: {
                    plugins: [require.resolve('react-refresh/babel')]
                  }
                }
              ]
            },
            ...rules
          ];
    
          compiler.options.module.rules = updatedRules;
        });
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 2021-04-05
      • 2019-12-22
      • 1970-01-01
      • 2019-10-11
      • 2014-01-30
      相关资源
      最近更新 更多