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

16 javascript webpack

我正在使用 Webpack 的 [hash] 来缓存破坏区域设置文件。但我还需要硬编码语言环境文件路径以从浏览器加载它。由于文件路径是用 [hash] 改变的,我需要注入这个值来获得正确的路径。

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

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

Dmi*_*nov 13

如果您想将哈希转储到文件并将其加载到服务器的代码中,您可以在您的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' }),
  ]
};

Run Code Online (Sandbox Code Playgroud)

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

{"hash":"64347f3b32969e10d80c"}
Run Code Online (Sandbox Code Playgroud)

我刚刚为这个插件创建了一个dumpmeta-webpack-plugin包。所以你可以改用它:

{"hash":"64347f3b32969e10d80c"}
Run Code Online (Sandbox Code Playgroud)

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


Wou*_*rgh 0

您可以使用将版本传递到您的构建webpack.DefinePlugin

如果你有一个带有版本的package.json,你可以像这样提取它:

const version = require("./package.json").version;
Run Code Online (Sandbox Code Playgroud)

例如(我们对版本进行了字符串化):

new webpack.DefinePlugin({
    'process.env.VERSION': JSON.stringify(version)
}),
Run Code Online (Sandbox Code Playgroud)

然后在您的 javascript 中,该版本将可用为:

process.env.VERSION
Run Code Online (Sandbox Code Playgroud)