How to inject Webpack build hash to application code

后端 未结 5 1336
花落未央
花落未央 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条回答
  •  -上瘾入骨i
    2021-01-04 09:08

    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.

提交回复
热议问题