一、新建目录best-test,初始化package.json并配置入口命令
cd best-test
npm init -y
// package.json 增加bin 命令
"bin": {
"best-test": "bin/index.js"
},
二、简单实现 best-test init 和 best-init --name 命令
#!/usr/bin/env node
// 注册一个命令 best-test init 和 best-test init --name
let commandList = {
init: (option, param) => {
console.log(`执行init流程:${option}=${param}`);
},
};
const argv = require('process').argv;
const command = argv[2]; // 接收第二个参数
const options = argv.slice(3); // options
if (options.length > 1) {
let [option, param] = options;
option = option.replace('--', '');
if (command) {
if (commandList[command]) {
commandList[command](option, param);
} else {
console.log('请输入正确的命令');
}
} else {
console.log('请输入命令');
}
}
// 实现参数解析 --version 和 -V
if (command && (command.startsWith('--') || command.startsWith('-'))) {
const globalOption = command.replace(/--|-/g, '');
if (globalOption === 'version' || globalOption === 'V') {
console.log('1.0.0');
}
}
console.log('best-test');
#!/usr/bin/env node
用于指明该脚本文件要使用node来执行,系统动态查找node;
平时开发,我们可以用which node 命令,查询node的安装文件目录。
三、本地调试
# 源npm包安装到本地;在工具库根目录执行
npm link
# 在npm目录下卸载 方法1
npm unlink "best-test"
# 方法2
npm uninstall -g best-test
# 在项目中使用 npm 包
npm link "best-test"
# 在项目中卸载 npm 包
npm unlink "best-test"
四、发布到npm
# 获取当前npm包镜像地址
npm get registry
# 淘宝源
https://registry.npmmirror.com/
# 设置官方地址(将源设置为淘宝的童鞋,记得切换一下)
npm config set registry https://registry.npmjs.org/
# 登录
npm login
# 发布包
npm publish
# 发布私有域的包
npm publish --access=public
# 24小时内可撤销包;删除已在 npm 发布的同名包,需要在24小时后才能重新发布
npm unpublish --force