如何将Webpack构建哈希值注入应用程序代码

如何将Webpack构建哈希值注入应用程序代码

本文介绍了如何将Webpack构建哈希值注入应用程序代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Webpack的[hash]缓存清除区域设置文件.但是我还需要对语言环境文件路径进行硬编码,以便从浏览器中加载它.由于文件路径已用[hash]更改,因此我需要注入此值以获取正确的路径.

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.

我不知道如何在配置中以编程方式获取Webpack [hash]值,因此我可以使用WebpackDefinePlugin注入它.

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

推荐答案

如果要将哈希转储到文件中并以服务器代码的形式加载,可以在 webpack.config中定义以下插件.js :

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' }),
  ]
};

输出 meta.json 文件的示例内容:

{"hash":"64347f3b32969e10d80c"}


我刚刚为此创建了一个 dumpmeta-webpack-plugin 程序包插入.因此,您可以改用它:


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,
      })
    }),
  ]
}

有关Stats对象的所有可用属性,请参考 Webpack文档.

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

这篇关于如何将Webpack构建哈希值注入应用程序代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:24