【问题标题】:WebPack repeatedly injects redundant script tags into index.html on loadWebPack 在加载时反复将冗余脚本标签注入 index.html
【发布时间】:2020-05-08 14:20:34
【问题描述】:

学习 WebPack 并将其设置为从模板创建 index.html 并使用包含唯一内容哈希的捆绑文件注入 <script> 标记(以绕过浏览器缓存并确保加载新内容),例如所以:bundle-[contentHash].js.

我正在使用 json-server 并将 webpack -d -w 作为 NPM 的脚本运行。当我运行脚本并加载页面时,它会不断地向 index.html 文件中添加相同的 <script> 标签。

webpack.config.js:

const webpack = require("webpack")
const path = require("path")
var htmlPlugin = require("html-webpack-plugin")

module.exports = {
  // context: path.resolve(__dirname),
  entry: "./client/index.jsx",
  output: {
    path: path.join(__dirname, "/public"),
    publicPath: path.join(__dirname, "/public"),
    filename: "bundle-[contentHash].js"
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [
    new htmlPlugin({
      template: "./public/index.html"
    })
  ]
}

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    重复的<script>标签注入是由于模板名称(index.html)与html-webpack-plugin的默认输出名称相同。

    将我的模板从 index.html 重命名为 template.html 解决了这个问题。

      plugins: [
        new htmlPlugin({
          template: "./public/template.html"
        })
      ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 2021-10-25
      • 2015-06-27
      • 2017-01-27
      • 2016-06-03
      • 2022-08-14
      • 1970-01-01
      相关资源
      最近更新 更多