HtmlWebpackPlugin 挂钩未在 CRA 中调用

问题描述 投票:0回答:0

我正在使用

react-scripts
4.0.3 和
react-app-rewired
2.1.6 对 webpack 配置进行一些调整。

我想更改生成并注入到

index.html
中的脚本标签的一些属性。我正在使用
alterAssetTags
HtmlWebpackPlugin
钩子。

class MyPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap('MyPlugin', compilation => {
      console.log('compilation'); // <- this is executed
      HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tap('MyPlugin', data => {
         console.log('adjust tags'); // <- not executed
      });
    });
  }
}

这是我的

config-overrides.js

const { override, addWebpackPlugin, babelInclude } = require("customize-cra");

module.exports = function (config, env) {
  return Object.assign(
    config,
    override(
      addWebpackPlugin(new MyPlugin()),
      babelInclude([
        path.resolve('src'), // don't forget this
      ])
    )(config, env)
  );
};

问题

问题是,在构建过程中没有调用

alterAssetTags
(但
compilation
钩子被调用)。

但是,如果我替换现有的 create-react-app

HtmlWebpackPlugin
,一切都会按预期进行。

const htmlWebpackPluginIndex = config.plugins.findIndex(plugin => plugin.constructor.name === 'HtmlWebpackPlugin');
const newHtmlWebpackPlugin = new HtmlWebpackPlugin({
   ...config.plugins[htmlWebpackPluginIndex].options,
 });
// Replace the original HtmlWebpackPlugin with the new instance
config.plugins.splice(htmlWebpackPluginIndex, 1, newHtmlWebpackPlugin);
config.plugins.push(new MyPlugin());

但这不是解决方案,因为生成的

index.html
不同。

问题

可能是什么问题,

alterAssetTags
没有被调用?

webpack create-react-app react-scripts html-webpack-plugin react-app-rewired
© www.soinside.com 2019 - 2024. All rights reserved.