UNPKG

makestatic-pack-webpack

Version:

Bundle assets using webpack

114 lines (95 loc) 3.36 kB
const when = require('when') const webpack = require('webpack') const PackPackWebpack = require('./lib/pack-plugin') const Config = require('./lib/config') /** * Bundles source file assets using webpack. * * @class PackWebpack */ class PackWebpack { /** * Configures the webpack compiler with system plugins. * * If the configuration option `pack` is disabled this function call is * a noop. * * If the `watch` configuration option is set the compiler watches source * files and the returned promise will never resolve. In this instance the * webpack plugin is responsible for executing the rest of the lifecycle at * the appropriate time. * * @function before * @member PackWebpack * @param {Object} context the processing context. * @param {Object} [options] plugin options. * * @returns a promise that resolves when compilation is complete. */ before (context, options = {}) { if (context.options.pack === false) { return } // if we are watching this will get set let watching = context.options.watch const log = context.log const packer = new PackPackWebpack(context, watching) const conf = new Config(context, options) const config = conf.getConfig({ plugins: [packer] }) const compiler = webpack(config) log.info('[webpack] %j', config.entry) return when.promise((resolve, reject) => { let watchOptions = config.watch || context.options.watch function onCompile (err, stat) { if (!err && stat && stat.compilation.errors.length) { err = stat.compilation.errors[0] } if (err) { // just print the error when watching /* istanbul ignore next: * * no need to mock this as we have nothing to assert on */ if (watching) { return console.error(err.stack || err.message) } // fall through to default error handling // will exit the program when running in the cli return reject(err) } let compileTime = (stat.endTime - stat.startTime) / 1000 let compiled = Object.keys(stat.compilation.assets) log.debug( '[webpack] %s', compiled.join(', ')) log.info('[webpack] %s files in %s s', compiled.length, compileTime) if (stat.compilation.errors.length) { for (let i = 0; i < stat.compilation.errors.length; i++) { log.debug(stat.compilation.errors[i]) } log.error('[webpack] errors %s', stat.compilation.errors.length) } // NOTE: we never resolve this promise as the webpack plugin // NOTE: will execute the lifecycle at the appropriate time (emit) /* istanbul ignore else: always in test env */ if (!watching || process.env.NODE_ENV === 'test') { resolve() } } if (watchOptions) { if (!(watchOptions instanceof Object)) { watchOptions = { aggregateTimeout: 300, poll: true } } // NOTE: assign to the context so that we can close it in the tests context.watcher = watching = compiler.watch(watchOptions, onCompile) } else { compiler.run(onCompile) } }) } } module.exports = PackWebpack