简体   繁体   English

WebPack 反复将冗余脚本标签注入 index.html 加载

[英]WebPack repeatedly injects redundant script tags into index.html on load

Learning WebPack and have set it up to create an index.html from a template and inject a <script> tag with a bundle file that includes a unique content hash (to bypass browser caching and ensure new content is loaded), like so: bundle-[contentHash].js .学习 WebPack 并设置它以从模板创建 index.html 并注入带有包含唯一内容 hash 的捆绑文件的<script>标记,并确保已加载新内容,例如:绕过浏览器缓存bundle-[contentHash].js

I'm using a json-server and running webpack -d -w as a script from NPM.我正在使用json-server并运行webpack -d -w作为 NPM 的脚本。 When I run the scripts and load the page, it continually adds identical <script> tags to the index.html file over and over.当我运行脚本并加载页面时,它会不断地将相同的<script>标签添加到 index.html 文件中。

webpack.config.js: 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"
    })
  ]
}

The repeated <script> tag injection was caused by having the name of the template (index.html) the same as the name of the default output of html-webpack-plugin .重复的<script>标签注入是由于模板的名称(index.html)与html-webpack-plugin的默认 output 的名称相同。

Renaming my template from index.html to template.html fixed the issue.将我的模板从index.html重命名为template.html解决了这个问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM