Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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: ***???***
      })
   ]
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
487 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...