How webpack configures script to add hashes

vue project, using simple template

the first figure shows the basic webpack configuration
clipboard.png

index.ejs
clipboard.png

question: how to configure, each package, config.js can add a hash value, so that the browser is not cached?

Mar.10,2022

html-webpack-plugin extension

refer to this article, customize a plug-in, add links to index.ejs or index.html files dynamically, and add random numbers to change the caching problem of static files.

Custom plug-ins in webpack.config.js

function MyPlugin(options) {
  this.options = options;
}

MyPlugin.prototype.apply = function(compiler) {
  var paths = this.options.paths;
  compiler.plugin('compilation', function(compilation, options) {
    compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) {
      for (var i = paths.length - 1; i >= 0; i--) {
        // "[hash]" 
        if(paths[i].indexOf("[hash]") != -1){
          let str = paths[i].replace("[hash]", new Date().getTime())
          htmlPluginData.assets.js.unshift(str);
        }else{
          htmlPluginData.assets.js.unshift(paths[i]);
        }

      }
      callback(null, htmlPluginData);
    });
  });
};




 plugins: [
    new MyPlugin({
      paths: [
        "./static/config.js?[hash]",
        "./static/vue.js"
      ]
    }),
    new HtmlWebpackPlugin({
      chunks: ['index'],
      inject: 'body',
      hash: true,
      title: '',
      filename: '../index.html',
      template: 'index.ejs',
    }),
   
  ],

clipboard.png

clipboard.png

:

clipboard.png


the name of the output resource in output can be filename: "[name]. [hash] .js",
just saw that webpack actually has three kinds of hash,

  1. hash
  2. chunkhash
  3. contenthash
Menu