Webpack Loaders - create and write files inside loader

帅比萌擦擦* 提交于 2020-05-17 08:11:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!