user9489527
user9489527

Reputation:

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 need to inject this value to get right path.

I don't know how can get Webpack [hash] value programmatically in config so I can inject it using WebpackDefinePlugin.

module.exports = (env) => {
  return {
   entry: 'app/main.js',
   output: {
      filename: '[name].[hash].js'
   }
   ...
   plugins: [
      new webpack.DefinePlugin({
         HASH: ***???***
      })
   ]
  }
}

Upvotes: 20

Views: 16878

Answers (7)

Réda Housni Alaoui
Réda Housni Alaoui

Reputation: 1445

You could use https://www.npmjs.com/package/build-hash-webpack-plugin :

import BuildHashPlugin from 'build-hash-webpack-plugin';
// ...
module.exports = {
    // ....
    plugins: [new BuildHashPlugin()]
}

The output is a JSON object in the form:

{"hash":"68aaedf27867fc4cb95d"}

Upvotes: 0

Oleksandr Oliynyk
Oleksandr Oliynyk

Reputation: 886

That can be done with Webpack Stats Plugin. It gives you nice and neat output file with all the data you want. And it's easy to incorporate it to the webpack config files where needed.

E.g. To get hash generated by Webpack and use it elsewhere. Could be achieved like:

# installation
npm install --save-dev webpack-stats-plugin
yarn add --dev webpack-stats-plugin
# generating stats file
const { StatsWriterPlugin } = require("webpack-stats-plugin")

module.exports = {
  plugins: [
    // Everything else **first**.

    // Write out stats file to build directory.
    new StatsWriterPlugin({
      stats: {
        all: false,
        hash: true,
      },
      filename: "stats.json" // Default and goes straight to your output folder
    })
  ]
}
# usage
const stats = require("YOUR_PATH_TO/stats.json");

console.log("Webpack's hash is - ", stats.hash);

More usage examples in their repo

Hope that helps!

Upvotes: 0

ZachB
ZachB

Reputation: 15366

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.

Upvotes: 2

VnDevil
VnDevil

Reputation: 1391

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

Upvotes: 2

Acidic
Acidic

Reputation: 6282

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.

Upvotes: 2

Dmitry Druganov
Dmitry Druganov

Reputation: 2358

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');

class MetaInfoPlugin {
  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 necessary
        hash: stats.hash
      };
      const json = JSON.stringify(metaInfo);
      return new Promise((resolve, reject) => {
        fs.writeFile(this.options.filename, json, 'utf8', error => {
          if (error) {
            reject(error);
            return;
          }
          resolve();
        });
      });
    });
  }
}

module.exports = {
  // ... your webpack config ...

  plugins: [
    // ... other plugins ...

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

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

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

Upvotes: 17

Wouter Coebergh
Wouter Coebergh

Reputation: 834

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

Upvotes: 0

Related Questions