build-scripts
Version:
scripts core
87 lines (86 loc) • 2.79 kB
JavaScript
;
const chalk_1 = require("chalk");
const Context_1 = require("../core/Context");
const webpackStats_1 = require("../utils/webpackStats");
const fs = require("fs-extra");
const path = require("path");
const log = require("../utils/log");
module.exports = async function ({ args, rootDir, eject, plugins, getBuiltInPlugins, }) {
const command = 'build';
const context = new Context_1.default({
args,
command,
rootDir,
plugins,
getBuiltInPlugins,
});
log.verbose('OPTIONS', `${command} cliOptions: ${JSON.stringify(args, null, 2)}`);
const { applyHook, rootDir: ctxRoot, webpack: webpackInstance } = context;
let configArr = [];
try {
configArr = await context.setUp();
}
catch (err) {
log.error('CONFIG', chalk_1.default.red('Failed to get config.'));
await applyHook(`error`, { err });
throw err;
}
await applyHook(`before.${command}.load`, { args });
// eject config
if (eject) {
return configArr;
}
if (!configArr.length) {
const errorMsg = 'No webpack config found.';
log.warn('CONFIG', errorMsg);
await applyHook(`error`, { err: new Error(errorMsg) });
return;
}
// clear build directory
const defaultPath = path.resolve(ctxRoot, 'build');
configArr.forEach(v => {
try {
const userBuildPath = v.chainConfig.output.get('path');
const buildPath = path.resolve(ctxRoot, userBuildPath);
fs.removeSync(buildPath);
}
catch (e) {
if (fs.existsSync(defaultPath)) {
fs.removeSync(defaultPath);
}
}
});
await applyHook(`before.${command}.run`);
const webpackConfig = configArr.map(v => v.chainConfig.toConfig());
let compiler;
try {
compiler = webpackInstance(webpackConfig);
}
catch (err) {
log.error('CONFIG', chalk_1.default.red('Failed to load webpack config.'));
await applyHook(`error`, { err });
throw err;
}
const result = await new Promise((resolve, reject) => {
// typeof(stats) is webpack.compilation.MultiStats
compiler.run((err, stats) => {
if (err) {
log.error('WEBPACK', (err.stack || err.toString()));
reject(err);
return;
}
const isSuccessful = webpackStats_1.default({
stats,
});
if (isSuccessful) {
resolve({
stats,
});
}
else {
reject(new Error('webpack compile error'));
}
});
});
await applyHook(`after.${command}.compile`, result);
};