我之前将 webpack 的 [hash] 值保存到了一个 meta.json 文件中:
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 = {
mode: 'production',
target: 'web',
...
plugins: [
new MetaInfoPlugin({ filename: './public/theme/assets/scripts/meta.json' }),
],
...
};
升级到 webpack 5 后,我收到了指示使用 contenthash 或其他值的弃用通知。[DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)
但是交换了.hash
以上部分带有 .contenthash
或任何其他哈希都不起作用。如何将 contenthash 保存到文件中,以便以后可以在模板系统中使用该值来链接文件?我基本上想要的是获得
[contenthash]
值转换为文本文件(json,任何格式),以便稍后在 PHP 模板系统中重用。
最佳答案
弃用通知即将使用[contenthash]
作为输出文件名。大概:
// ...
output: {
path: path.resolve(process.cwd(), 'dist'),
filename: utils.isProd() ? '[name].[contenthash].js' : '[name].js',
// ...
},
创建 filelist.json 使用自己的插件将编译后的文件名写入 webpacks 输出文件夹:
class FileListPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync('FileListPlugin', (compilation, callback) => {
var a = { files: [] };
// build filename array
for (var filename in compilation.assets)
a.files.push(filename);
// build js and css childs
for (var filename in compilation.assets) {
var f = filename.split('.');
var filetype = f[f.length - 1];
if (filetype === 'css' || filetype === 'js')
a[filetype] = {
filename: filename,
hash: f[f.length - 2]
};
}
// a to string
a = JSON.stringify(a);
// Insert this list into the webpack build as a new file asset:
compilation.assets['filelist.json'] = {
source: () => { return a },
size: () => { return a.length }
};
callback();
});
}
}
这是对这个例子的修改 https://webpack.js.org/contribute/writing-a-plugin/#example注册插件:
plugins: [
//...
new FileListPlugin(),
//...
]
filelist.json 的内容如下所示:{
"files": [
"main.d060b15792a80dc111ee.css",
"main.0f88c5f5cb783c5a385f.js",
"layout.pug"
],
"css": {
"filename": "main.d060b15792a80dc111ee.css",
"hash": "d060b15792a80dc111ee"
},
"js": {
"filename": "main.0f88c5f5cb783c5a385f.js",
"hash": "0f88c5f5cb783c5a385f"
}
}
关于webpack - 如何在 webpack 配置中保存 contenthash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64740434/