简体   繁体   中英

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: ***???***
      })
   ]
  }
}

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.

在服务器上,您可以通过从包文件夹中读取文件名(例如:web.bundle.f4771c44ee57573fabde.js)来获取哈希值。

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.

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

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.

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.

Eg 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM