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.
Asked
Active
Viewed 844 times
0

woojoo666
- 7,801
- 7
- 45
- 57
1 Answers
2
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
};

woojoo666
- 7,801
- 7
- 45
- 57
-
So what is the different between `fs.writeFileSync` and `this.emitFIle` ? – Does Mar 12 '22 at 07:17
-
@Does It won't be overwritten if you set up Webpack to clean up the dist folder on every build. Also, it has a context of the dist folder, so you worry less about the correct filepath – Codeartist May 22 '22 at 22:54