webpack 如何配置script添加哈希值

vue项目,用的是simple模板

第一张图是webpack基本配置
clipboard.png

第二张图是index.ejs模板,打包的时候会用到
clipboard.png

问题:如何配置,每次打包,config.js能加上哈希值,让浏览器不被缓存?

阅读 6.3k
2 个回答

html-webpack-plugin扩展插件

参考了这篇文章,自定义了了一个插件,往index.ejs或index.html文件动态加入链接,添加随机数即可改变静态文件的缓存问题。

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

在output 中的输出资源名字可以用 filename: "[name].[hash].js",
刚看到,其实webpack 有三种hash ,

  1. hash
  2. chunkhash
  3. contenthash
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题