【问题标题】:HtmlWebpackPlugin: wrong hash for script file is injected into html fileHtmlWebpackPlugin:脚本文件的错误哈希被注入到 html 文件中
【发布时间】:2021-05-02 21:34:46
【问题描述】:

我正在尝试使用 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/',
            },
          },
        ],
      },
    ],
  },
};


这是生成的 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>

这是我的 dist 文件夹:

如你所见,bundle 文件名是可以的,但是body 和的script 标签有错误的src

【问题讨论】:

  • 我也有同样的问题。希望有人知道解决方案!

标签: javascript webpack html-webpack-plugin


【解决方案1】:

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

在 webpack 配置文件的优化部分,将 realContentHash 设置为 false

optimization: {
    // other config ...
    realContentHash: false,
},

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2011-02-24
    • 2021-04-07
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多