如何在webpack配置中保存contenthash



我之前将webpack的[哈希]值保存到一个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' }),
],
...
};

在升级到webpack5之后,我收到了反对通知,指出要使用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',
// ...
},

创建文件列表.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"
}
}

最新更新