I previously saved the [hash] value of webpack to a meta.json file:
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' }),
],
...
};
After upgrading to webpack 5 I receive deprecation notices that point to using contenthash or other values instead.
[DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)
But exchanging the .hash
part above with .contenthash
or any of the other hashes won't work. How do I save the contenthash to a file so I can later on use the value in a templating system to so link the file?
What I am basically trying is to get the [contenthash]
value into a text file (json, whatever format) to reuse in a PHP templating system later on.
The deprecation notice is about to use [contenthash]
as output filename. Just about:
// ...
output: {
path: path.resolve(process.cwd(), 'dist'),
filename: utils.isProd() ? '[name].[contenthash].js' : '[name].js',
// ...
},
Create filelist.json
Writing the compiled filenames with an own plugin to webpacks output folder:
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();
});
}
}
It's a modification from this example https://webpack.js.org/contribute/writing-a-plugin/#example
Register plugin:
plugins: [
//...
new FileListPlugin(),
//...
]
The content of filelist.json looks then like this:
{
"files": [
"main.d060b15792a80dc111ee.css",
"main.0f88c5f5cb783c5a385f.js",
"layout.pug"
],
"css": {
"filename": "main.d060b15792a80dc111ee.css",
"hash": "d060b15792a80dc111ee"
},
"js": {
"filename": "main.0f88c5f5cb783c5a385f.js",
"hash": "0f88c5f5cb783c5a385f"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With