From 7a69cff30c82c08072bfd84c347e58fd87f80994 Mon Sep 17 00:00:00 2001 From: endiliey Date: Wed, 8 Aug 2018 00:45:43 +0800 Subject: [PATCH] feat: add build command --- lib/commands/build.js | 56 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/lib/commands/build.js b/lib/commands/build.js index 0005a7c1ed..abc9be7068 100644 --- a/lib/commands/build.js +++ b/lib/commands/build.js @@ -1,6 +1,60 @@ +const webpackNiceLog = require('webpack-nicelog'); +const webpack = require('webpack'); +const path = require('path'); +const chalk = require('chalk'); +const load = require('../load'); +const createProdConfig = require('../webpack/prod'); + +function compile(config) { + return new Promise((resolve, reject) => { + webpack(config, (err, stats) => { + if (err) { + return reject(err); + } + if (stats.hasErrors()) { + stats.toJson().errors.forEach(e => { + console.error(e); + }); + reject(new Error(`Failed to compile with errors.`)); + return false; + } + if (stats.hasWarnings()) { + stats.toJson().warnings.forEach(warning => { + console.warn(warning); + }); + } + resolve(stats.toJson({modules: false})); + return true; + }); + }); +} + module.exports = async function build(siteDir, cliOptions = {}) { process.env.NODE_ENV = 'production'; console.log('Build command invoked ...'); - console.log(siteDir); console.log(cliOptions); + + const props = await load(siteDir); + + // resolve webpack config + let config = createProdConfig(props); + config.plugin('WebpackNiceLog').use(webpackNiceLog, [ + { + name: 'Production' + } + ]); + + // create compiler from generated webpack config + config = config.toConfig(); + + // compile! + await compile(config); + + const {outDir} = props; + const relativeDir = path.relative(process.cwd(), outDir); + console.log( + `\n${chalk.green('Success!')} Generated static files in ${chalk.cyan( + relativeDir + )}.\n` + ); };