webpack v4.0.0+
node v8.12.0
目标
使用 webpack node api 封装一个脚手架 chh-cli
,支持这些功能,
- 终端执行
chh
命令时,对文件进行打包
项目初始化
# 创建项目目录,然后初始化项目
$ mkdir chh-cli && cd chh-cli
$ npm init
# 安装 webpack
$ npm install --save webpack
在 package.json
文件中,添加上 bin 字段,
{
"name": "chh-cli",
"version": "1.0.0",
"description": "使用 webpack node api 封装脚手架",
"main": "src/index.js",
"bin": {
"chh": "bin/index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
使用 webpack node api 封装脚手架
const path = require('path');
const webpack = require('webpack');
const config_name = 'config.js';
const config_url = path.resolve(process.cwd(), config_name); // process.cwd() 运行node的工作目录
const config = require(config_url);
const compiler = webpack(config);
compiler.run((err, stats) => {
// 在这里处理错误
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
// 统计信息(stats)文档
// https://webpack.docschina.org/configuration/stats
const info = stats.toJson("none");
if (stats.hasErrors()) {
info.errors.forEach((item, idx) => {
console.error(item);
});
return;
}
if (stats.hasWarnings()) {
// info.warnings.forEach((item, idx) => {
// console.warn(item);
// });
}
// 记录结果...
console.log(stats.toString({
colors: true,
}));
});
全局安装与卸载
# 全局安装
$ npm install -g .
# 全局卸载
$ npm rm -g chh-cli
参考文档
webpack api 使用引导:https://webpack.docschina.org/api/
webpack Node.js API:https://webpack.docschina.org/api/node