webpack v4.0.0+
node v8.12.0

目标

使用 webpack node api 封装一个脚手架 chh-cli,支持这些功能,

  • 终端执行 chh 命令时,对文件进行打包

项目初始化

  1. # 创建项目目录,然后初始化项目
  2. $ mkdir chh-cli && cd chh-cli
  3. $ npm init
  4. # 安装 webpack
  5. $ npm install --save webpack

package.json 文件中,添加上 bin 字段,

  1. {
  2. "name": "chh-cli",
  3. "version": "1.0.0",
  4. "description": "使用 webpack node api 封装脚手架",
  5. "main": "src/index.js",
  6. "bin": {
  7. "chh": "bin/index.js"
  8. },
  9. "scripts": {
  10. "test": "echo \"Error: no test specified\" && exit 1"
  11. },
  12. "author": "",
  13. "license": "ISC"
  14. }

使用 webpack node api 封装脚手架

  1. const path = require('path');
  2. const webpack = require('webpack');
  3. const config_name = 'config.js';
  4. const config_url = path.resolve(process.cwd(), config_name); // process.cwd() 运行node的工作目录
  5. const config = require(config_url);
  6. const compiler = webpack(config);
  7. compiler.run((err, stats) => {
  8. // 在这里处理错误
  9. if (err) {
  10. console.error(err.stack || err);
  11. if (err.details) {
  12. console.error(err.details);
  13. }
  14. return;
  15. }
  16. // 统计信息(stats)文档
  17. // https://webpack.docschina.org/configuration/stats
  18. const info = stats.toJson("none");
  19. if (stats.hasErrors()) {
  20. info.errors.forEach((item, idx) => {
  21. console.error(item);
  22. });
  23. return;
  24. }
  25. if (stats.hasWarnings()) {
  26. // info.warnings.forEach((item, idx) => {
  27. // console.warn(item);
  28. // });
  29. }
  30. // 记录结果...
  31. console.log(stats.toString({
  32. colors: true,
  33. }));
  34. });

全局安装与卸载

  1. # 全局安装
  2. $ npm install -g .
  3. # 全局卸载
  4. $ npm rm -g chh-cli

参考文档