准备工作
1.有一个自己得github账号
2.准备node环境
3.了解一下commander模块与inquirer模块
4.在自己的github提前创建好项目模板
现在主流得cli脚本都是项目模板与cli执行脚本是分离得,
我们使用commader模块获取 cli 执行语句后面得参数,
(比如我得cli叫 dmh-cli, dmh-cli test ) commader可以很方便帮我们获取到test这个参数,
commader还有很多功能不一一解答,
然后inquirer是根据用户得喜好进行配置
本地测试需要创建一个软连接 npm link
最后可以通过npm pulish发布我们得cli
#!/usr/bin/env node
const path = require('path')
const { program } = require('commander')
const inquirer = require('inquirer')
const childProcess = require('child_process')
program
.arguments('<dir>')
.description('this is folder')
.action(dir => {
inquirer.prompt(
[
{
type: 'list',
name: 'framework',
message: 'whick framework do you like',
choices: [
'vue',
'react'
]
}
]).then(answers => {
const fullDir = path.resolve(process.cwd(), dir)
let command = ''
if (answers.framework === 'vue') {
command = 'git clone http://xxx' + ' ' + fullDir
} else {
command = 'git clone http://xxx' + ' ' + fullDir
}
childProcess.execSync(command)
})
})
program.parse(process.argv)
package.json里面得配置要做下小改动, 添加一个bin可执行文件
{
"name": "dmh-cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"bin": {
"dmh-cli": "./index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"commander": "^6.1.0",
"inquirer": "^7.3.3"
}
}
网友评论