我正在使用 Webpack 的 [hash] 缓存破坏区域设置文件。但我还需要硬编码语言环境文件路径以从浏览器加载它。由于文件路径已用 [hash] 更改,我需要注入(inject)此值以获得正确的路径。
我不知道如何在配置中以编程方式获取 Webpack [哈希] 值,以便我可以使用 WebpackDefinePlugin 注入(inject)它。
module.exports = (env) => {
return {
entry: 'app/main.js',
output: {
filename: '[name].[hash].js'
}
...
plugins: [
new webpack.DefinePlugin({
HASH: ***???***
})
]
}
}
最佳答案
如果您想将散列转储到一个文件并将其加载到您的服务器代码中,您可以在您的 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这个插件的包。所以你可以改用它:
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,
})
}),
]
}
请引用Webpack documentation对于 Stats 对象的所有可用属性。
关于javascript - 如何将 Webpack 构建哈希注入(inject)应用程序代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228128/