目录结构:
myApp
-bin
mypack.js
-lib
Compiler.js
-template
bound.ejs
package.json
package-lock.json
// 配置 /bin/mypack.js
#!/usr/bin/env node
/*
1.创建bin目录, 将打包主程序放入其中
主程序顶部添加'#!/usr/bin/env node'标识, 指定执行环境为node环境
2.在package.json中添加bin脚本, pack--键指定命令名称, 值 指定执行主程序的目录
"bin":{
"pack": "./bin/pack.js"
}
3.通过npm link到全局包,供本地使用
*/
const path = require('path');
// root为执行node所在目录; __dirname为当前mypack.js所在目录
const root = process.cwd();
// 导入配置文件
const config = require(path.resolve(root, 'webpack.config.js'))
const Compiler = require('../lib/Compiler');
new Compiler(config).start()
// 配置 package.json
{
"name": "mypack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
//这里需要添加bin配置
"bin": {
"mypack": "./bin/mypack.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/generator": "^7.12.15",
"@babel/parser": "^7.12.16",
"@babel/traverse": "^7.12.13",
"tapable": "^2.2.0"
},
"devDependencies": {
"ejs": "^3.1.6"
}
}