自己写一个cli
- npm init --yes 初始化一个node的环境
- 创建index.js 输入
#!/usr/bin/env node
console.log("hello cli")
- 修改packagejson加入
"bin":{
"mycli":"./index.js"
},
npm link 连接到全局
修改index.js 中为 console.log(process.argv)
执行mycli 打印出[ '/usr/local/bin/node', '/usr/local/bin/mycli' ]
执行 mycli --flag arg2 arg3 打印出
[
'/usr/local/bin/node',
'/usr/local/bin/mycli',
'--flag',
'arg2',
'arg3'
]安装插件 npm install commander inquirer
commander
const {program} = require("commander")
program
.arguments('<dir>')// [] 可填 <>必填
.description("this is a directory!")
.action((dir)=>{
console.log('dir',dir)
})
program.parse(process.argv)
- inquirer 表单选择
const {program} = require("commander")
const inquirer = require("inquirer")
program
.arguments('<dir>')// [] 可填 <>必填
.description("this is a directory!")
.action((dir)=>{
return inquirer.prompt([
{
type:'list',
name:'framework',
message:'which framework do you like?',
choices:[
"react",
"vue"
]
}
]).then((answers)=>{
console.log('result',dir,answers)
// fs.writeFileSync() 区分不同选择,创建不同文件,写入不同内容,
// 实际 可以将这部分文件单独放在git上,即使安装最新cli也可以下载
// git clone xxx dir
})
})
program.parse(process.argv)
// mycli test
// ? which framework do you like? react
// result test { framework: 'react' }
- demo完整版
#!/usr/bin/env node
const {program} = require("commander")
const inquirer = require("inquirer")
const fs = require('fs')
const path = require("path")
const childProcess = require("child_process")
program
.arguments('<dir>')// [] 可填 <>必填
.description("this is a directory!")
.action((dir)=>{
return inquirer.prompt([
{
type:'list',
name:'framework',
message:'which framework do you like?',
choices:[
"react",
"vue"
]
}
]).then((answers)=>{
// fs.writeFileSync() 区分不同选择,创建不同文件,写入不同内容,
// 实际 可以将这部分文件单独放在git上,即使安装最新cli也可以下载
// git clone xxx dir
const fullDir = path.resolve(process.cwd(),dir)
console.log("dir",fullDir);
const command = `git clone https://github.com/XXX/${answers.framework}-XXX.git ${fullDir}`
childProcess.execSync(command)
})
})
program.parse(process.argv)
- 发布 npm publish