Skip to content

Instantly share code, notes, and snippets.

@kisenka
Last active April 15, 2023 15:09
Show Gist options
  • Save kisenka/3513c2fe859e11e1d04428a21b27c6dd to your computer and use it in GitHub Desktop.
Save kisenka/3513c2fe859e11e1d04428a21b27c6dd to your computer and use it in GitHub Desktop.
Webpack in-memory filesystem
var webpack = require('webpack');
var MemoryFS = require('memory-fs');
var SingleEntryDependency = require('webpack/lib/dependencies/SingleEntryDependency');
var fs = new MemoryFS();
fs.mkdirpSync('/src');
fs.writeFileSync('/src/app.js', 'require("./dep.js")', 'utf-8');
fs.writeFileSync('/src/dep.js', 'module.exports = function(msg){console.log(msg)}', 'utf-8');
fs.writeFileSync('/src/extra-entry.js', 'require("./dep.js")', 'utf-8');
var compiler = webpack({
context: '/src',
entry: {app: './app.js'},
output: {
filename: '[name].js',
path: '/build'
}
});
compiler.inputFileSystem = fs;
compiler.outputFileSystem = fs;
compiler.resolvers.normal.fileSystem = fs;
compiler.resolvers.context.fileSystem = fs;
compiler.plugin('make', function(compilation, done) {
var dep = new SingleEntryDependency('./extra-entry.js');
dep.loc = 'extra-entry';
compilation.addEntry('/src', dep, 'extra-entry', done);
});
compiler.run(function(err, stats) {
if (err) throw err;
console.log(stats.compilation.assets['app.js'].source());
});
@tokrex
Copy link

tokrex commented Dec 8, 2021

Thanks! Great Gist!

As a side note. Webpack 5 uses compiler.intermediateFileSystem = fs; instead of compiler.resolvers.normal and compiler.resolvers.context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment