Skip to content

Instantly share code, notes, and snippets.

@mark-bradshaw
Created October 8, 2015 17:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mark-bradshaw/ce2d449e30a856fe3b41 to your computer and use it in GitHub Desktop.
Save mark-bradshaw/ce2d449e30a856fe3b41 to your computer and use it in GitHub Desktop.
Use an in-memory webpack compiler to get specific files or file trees.
import _ from 'lodash';
import MemoryFileSystem from 'memory-fs';
import webpack from 'webpack';
import webpackConfig from '../../webpack.config';
// This function allows you to do an on-the-fly, in-memory webpack compile starting
// with whatever file entry point you want, and receive back the compiled object.
export default (entry, callback) => {
let config = _.clone(webpackConfig);
config.watchOptions = {};
config.entry.length = 0;
config.entry[0] = entry;
const compiler = webpack(config);
const memFs = compiler.outputFileSystem = new MemoryFileSystem();
const handleCompilerOutput = err => {
if (err) {
console.log('error', err);
return callback(err);
}
const outputPath = `${compiler.options.output.path}/${compiler.options.output.filename}`;
const packedOutput = memFs.readFileSync(outputPath);
const compiledObject = eval(packedOutput.toString());
callback(null, compiledObject);
};
if (process.env.NODE_ENV !== 'production') {
// If we are in dev mode, keep watching for file changes and re-run this.
compiler.watch({}, handleCompilerOutput);
} else {
compiler.run(handleCompilerOutput);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment