[英]Webpack Loaders - create and write files inside loader
Pretty much what the title suggests. 标题说明的内容差不多。 I want to create a metadata file alongside every javascript file in my project. 我想在项目中的每个javascript文件旁边创建一个元数据文件。 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. 因此,我需要一个完全不改变内容的webpack加载器,仅提取一些元数据并将其写入文件中。 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. fs.writeFileSync
似乎可以正常工作,但是我不知道是否应该使用它,因为似乎某些webpack指南建议使用称为memory-fs
东西,即webpack的内存中文件系统。
So this took a while to find and seems rarely mentioned, but webpack loaders actually have a method this.emitFile
specifically for this purpose. 因此,这花了一段时间才发现,而且似乎很少提及,但是webpack加载器实际上有专门用于此目的的this.emitFile
方法。 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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.