How to inject Webpack build hash to application code

后端 未结 5 1367
花落未央
花落未央 2021-01-04 08:29

I\'m using Webpack\'s [hash] for cache busting locale files. But I also need to hard-code the locale file path to load it from browser. Since the file path is altered with [

5条回答
  •  渐次进展
    2021-01-04 09:10

    Seems like it should be a basic feature but apparently it's not that simple to do.

    You can accomplish what you want by using wrapper-webpack-plugin.

    plugins: [
      new WrapperPlugin({
        header: '(function (BUILD_HASH) {',
        footer: function (fileName) {
          const rx = /^.+?\.([a-z0-9]+)\.js$/;
          const hash = fileName.match(rx)[1];
          return `})('${hash}');`;
        },
      })
    ]
    

    A bit hacky but it works — if u don't mind the entire chunk being wrapped in an anonymous function. Alternatively you can just add var BUILD_HASH = ... in the header option, though it could cause problem if it becomes a global.

    I created this plugin a while back, I'll try to update it so it provides the chunk hash naturally.

提交回复
热议问题