问题描述
我正在使用 Webpack 的 [hash] 来缓存破坏区域设置文件.但我还需要硬编码语言环境文件路径以从浏览器加载它.由于文件路径是用 [hash] 改变的,我需要注入这个值来获得正确的路径.
我不知道如何在配置中以编程方式获取 Webpack [hash] 值,以便我可以使用 WebpackDefinePlugin 注入它.
module.exports = (env) =>{返回 {条目:'app/main.js',输出: {文件名:'[名称].[哈希].js'}...插件: [新的 webpack.DefinePlugin({哈希:***???***})]}}
如果您想将哈希转储到文件并加载到服务器代码中,您可以在 webpack.config 中定义以下插件.js
:
const fs = require('fs');类元信息插件{构造函数(选项){this.options = { 文件名: 'meta.json', ...options };}应用(编译器){compiler.hooks.done.tap(this.constructor.name, stats => {常量元信息 = {//如有必要,添加任何其他信息哈希:stats.hash};const json = JSON.stringify(metaInfo);返回新的承诺((解决,拒绝)=> {fs.writeFile(this.options.filename, json, 'utf8', error => {如果(错误){拒绝(错误);返回;}解决();});});});}}模块.出口 = {//... 你的 webpack 配置 ...插件: [//... 其他插件 ...新元信息插件({文件名:'dist/meta.json'}),]};
输出meta.json
文件的示例内容:
{"hash":"64347f3b32969e10d80c"}
我刚刚为此创建了一个 dumpmeta-webpack-plugin 包插入.所以你可以改用它:
const { DumpMetaPlugin } = require('dumpmeta-webpack-plugin');模块.出口 = {...插件: [...新的 DumpMetaPlugin({文件名:'dist/meta.json',准备:统计=>({//添加您需要转储的任何其他信息哈希:stats.hash,})}),]}
有关 Stats 对象的所有可用属性,请参阅 Webpack 文档.>
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: ***???***
})
]
}
}
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.
这篇关于如何将 Webpack 构建哈希注入应用程序代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!