问题
Pretty much what the title suggests. I want to create a metadata file alongside every javascript file in my project. So I need a webpack loader that doesn't change the content at all, and just extracts some metadata and writes it to a file. What's the best way to do this? fs.writeFileSync
seems to work fine, but I don't know if I should use it since it seems like some webpack guides recommend using something called memory-fs, webpack's in-memory filesystem.
回答1:
So this took a while to find and seems rarely mentioned, but webpack loaders actually have a method this.emitFile specifically for this purpose. Here is some example usage:
function extractMeta(content) {
// extract and return metadata for file
}
module.exports = function(content) {
console.log('extracting metadata and writing to file');
// get source filename, strip file extension and append ".meta"
const filename = this.resourcePath.split('/').pop().split('.')[0] + '.meta'
this.emitFile(filename, extractMeta(content));
return content; // return the source file unchanged
};
来源:https://stackoverflow.com/questions/57617060/webpack-loaders-create-and-write-files-inside-loader