HtmlWebpackPlugin:脚本文件的错误哈希值被注入到 html 文件中

Ham*_*ari 4 javascript webpack html-webpack-plugin

我正在尝试使用 HtmlWebpackPlugin 生成 .HTML 文件

当使用 webpack 运行构建时,我遇到以下问题:HTML 文件中脚本标记的 src 与脚本文件名不同

这是我的 webpack 配置:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  entry: { index: path.resolve(__dirname, '../src/index.js') },
  output: {
    filename: 'bundle.[fullhash].js',
    path: path.resolve(__dirname, '../dist/'),
  },
  devtool: 'source-map',
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '../src/index.html'),
      minify: true,
    }),
  ],
  module: {
    rules: [
      // HTML
      {
        test: /\.(html)$/,
        use: ['html-loader'],
      },

      // JS
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },

      // CSS
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },

      // Images
      {
        test: /\.(jpg|png|gif|svg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets/images/',
            },
          },
        ],
      },
    ],
  },
};


Run Code Online (Sandbox Code Playgroud)

这是生成的 HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Document</title>
    <script
      defer="defer"
      src="bundle.3d5baadb547d13677f00.js?3d5baadb547d13677f00"
    ></script>
  </head>
  <body>

    <script src="1ec740dc7ce75155c1fd.js"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是我的 dist 文件夹:

dist 文件夹

正如你所看到的,bundle 文件的名称是可以的,但是正文的 和 的 script 标签的 src 是错误的

小智 5

我在这个 Github 问题的评论中找到了解决方案:https ://github.com/jantimon/html-webpack-plugin/issues/1638

在 webpack 配置文件的优化部分中,设置realContentHashfalse

optimization: {
    // other config ...
    realContentHash: false,
},
Run Code Online (Sandbox Code Playgroud)

例如,我的 webpack 配置对象如下所示:

{
    mode: ...,
    entry: ...,
    output: ...,
    module: ...,
    plugins: ...,
    optimization: {
        minimizer: [new CssMinimizerPlugin(), "..."],  // other config
        realContentHash: false,
    }
}
Run Code Online (Sandbox Code Playgroud)

这有时会产生次优的情况,即哈希值的变化超过必要的程度,但它似乎是目前最好的解决方案(待对该问题进行更新。)