Created
October 8, 2015 17:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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