node环境
commander - 用于定义命令
chalk - 让命令行的字符带上颜色
创建项目
npm init -y
{
"name": "shell",
"version": "1.0.0",
"description": "",
"main": "index.js",
+ "bin": {
+ "myshell": "index.js"
+ },
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
npm install commander inquirer chalk
touch index.js
index.js
const cmd = require('commander')
const inquirer = require('inquirer')
const chalk = require('chalk')
console.log('2')
index.js 第一行加入 识别运行环境
#!/usr/bin/env node
npm link // 在模块创建链接 可本地调试 一般只要一次就行了,文件保存自动更新
myshell // mys
一个自定义基本的本地测试命令行就可以了,上线的话就npm login npm publish (不需要npm link)
注意 package-lock.json 有可能导致下载错误
rm package-lock.json
npm cache clear --force
最好依赖包也删了
chalk
console.log(chalk.red('测试一'))
console.log(chalk.yellow('测试二'))
commander
cmd.version('1.0.0','-V --version')
cmd.parse(process.argv) // 解析命令行参数,不可少
// 自定义参数
cmd.command('init <name>').action((name)=>{
inquirer.prompt([
{
type:"input",
name:"projectname",
message:"项目的名字是什么"
}
]).then((answer)=>{
console.log(answer)
})
})