简体   繁体   中英

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 .

I'm using a json-server and running webpack -d -w as a script from NPM. When I run the scripts and load the page, it continually adds identical <script> tags to the index.html file over and over.

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 .

Renaming my template from index.html to template.html fixed the issue.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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