Skip to content Skip to sidebar Skip to footer

How To Inject Webpack Build Hash To Application Code

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 [hash], I

Solution 1:

In case you want to dump the hash to a file and load it in your server's code, you can define the following plugin in your webpack.config.js:

const fs = require('fs');

classMetaInfoPlugin {
  constructor(options) {
    this.options = { filename: 'meta.json', ...options };
  }

  apply(compiler) {
    compiler.hooks.done.tap(this.constructor.name, stats => {
      const metaInfo = {
        // add any other information if necessaryhash: stats.hash
      };
      const json = JSON.stringify(metaInfo);
      returnnewPromise((resolve, reject) => {
        fs.writeFile(this.options.filename, json, 'utf8', error => {
          if (error) {
            reject(error);
            return;
          }
          resolve();
        });
      });
    });
  }
}

module.exports = {
  // ... your webpack config ...plugins: [
    // ... other plugins ...newMetaInfoPlugin({ filename: 'dist/meta.json' }),
  ]
};

Example content of the output meta.json file:

{"hash":"64347f3b32969e10d80c"}

I've just created a dumpmeta-webpack-plugin package for this plugin. So you might use it instead:

const { DumpMetaPlugin } = require('dumpmeta-webpack-plugin');

module.exports = {
  ...

  plugins: [
    ...

    newDumpMetaPlugin({
      filename: 'dist/meta.json',
      prepare: stats => ({
        // add any other information you need to dumphash: stats.hash,
      })
    }),
  ]
}

Please refer to the Webpack documentation for all available properties of the Stats object.

Solution 2:

On server, you can get the hash by reading the filenames (example: web.bundle.f4771c44ee57573fabde.js) from your bundle folder.

Solution 3:

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: [
  newWrapperPlugin({
    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.

Solution 4:

You can pass the version to your build using webpack.DefinePlugin

If you have a package.json with a version, you can extract it like this:

const version = require("./package.json").version;

For example (we stringified the version):

new webpack.DefinePlugin({
    'process.env.VERSION': JSON.stringify(version)
}),

then in your javascript, the version will be available as:

process.env.VERSION

Solution 5:

The WebpackManifestPlugin is officially recommended in the output management guide. It writes a JSON to the output directory mapping the input filenames to the output filenames. Then you can inject those mapped values into your server template.

It's similar to Dmitry's answer, except Dmitry's doesn't appear to support multiple chunks.

Post a Comment for "How To Inject Webpack Build Hash To Application Code"