tj-cli
以tj-cli为例,介绍如何搭建cli
必备模块
- commander: 参数解析
--help
就是借助于commander - inquirer: 交互式命令行工具,实现命令行的选择功能
- download-git-repo: 在git中下载模板
- chalk: 改变console输出内容的颜色
- metalsmith:读取所有we年,实现模板渲染
- consolidate: 统一模板引擎
步骤
npm link
使用npm link
将tj-cli链接到全局
eslint
安装eslint
js npm i eslint npx eslint --init
在eslint开启关闭某个校验项使用数字 0, 1, 2
- 0: 关闭
- 1: 警告
- 2: 错误
commander
安装及使用
// 安装
npm i commander
// 使用
const program = require('commander');
program.parse(process.argv);
命令配置
program
.command(create'') //配置命令的名字
.alias('c') // 配置命令的参数
.description('TyrionJYQ personal CLI') // 命令描述
.action(() => {
console.log('TyrionJYQ') // 命令动作
})
在创建多个命令时,可以先将需要设置的命令用对象来描述,然后遍历对象,调用
program
生成命令
module.exports = {
create: {
alias: 'c',
description: 'create a new project',
examples: [
'tj-cli create <project-name>',
],
},
config: {
alias: 'conf',
description: 'config project varible',
examples: [
'tj-cli config set <key> <value>',
'tj-cli config get <key>',
],
},
'*': {
alias: '',
description: 'command not found',
examples: [],
},
}
下载模板
使用axios下载模板
npm install axios
// 个人仓库
const fetcherUserReposUrl = 'https://api.github.com/users/TyrionJYQ/repos'
// 组织仓库
const fetcherOrgReposUrl = 'https://api.github.com/orgs/:orgName/repos'
加载动画
使用ora显示加载动画
安装
npm install ora
使用
const spinner = ora('download...')
spinner.start() //开启动画
spinner.succeed() // 关闭动画
问询
安装
npm install inquirer
使用
const {repo} = await Inquirer({
name: 'repo',
type: 'list',
message: 'choice a repo',
choices: repos,
})
问询是一个等待用户选择,所以这是一个异步事件