windows 系统用node编写cli的方法
2019-06-25 本文已影响0人
游民小龙虾
1.新建项目根目录,在根目录下用npm init 命令初始化项目(生成package.json文件);
2.在pckage.json文件里添加bin字段:
{
"name": "uat",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"//uat 为命令名称, index.js为在命令行工具中输入uat后node将会执行的js文件
},
"bin": {
"uat": "./index.js"
},
"author": "",
"license": "ISC"
}
3.在项目的相应位置新建index.js文件,编写cli代码。
#!/usr/bin/env node //这一句是必要的
console.log('hello world');
4.执行npm link命令安装cli。
5.在命令行工具中输入uat测试cli是否安装成功。
编写cli时比较有用的前端库: commander.js(文档地址:https://www.npmjs.com/package/commander)