有哪些CLI?
- Vue-cli
- Gulp
- create-react-app
- webpack
- yeoman
- express-generator
- ...
为什么需要CLI?
- 减少重复性工作。
- 根据动态命令更方便的生成开发环境。
- 团队协同,效率高。
我们要达到的设计?
-
Node-Simple-BFF-Architecture init node-BFF
-
Node-Simple-BFF-Architecture list
最终的效果图
步骤:
一. 新建文件,进入文件夹 npm init
二. 在package.json文件夹下加入:
bin:{
"Node-Simple-BFF-Architecture": "./bin/index.js"
}
复制代码
三.在目录下新建文件夹 bin,在bin下新建index.js
四. 执行命令: npm link
复制代码
五.在index.js文件夹下写入:
#!/usr/bin/env node
//1.获取用户输入的命令
console.log(process.argv)
复制代码
六. 在控制台执行:
Node-Simple-BFF-Architecture
复制代码
便可以看见控制台有这个Node-Simple-BFF-Architecture命令了。
七. 代码(我都有注释):
#!/usr/bin/env node
//逻辑:
//1.获取用户输入的命令 console.log(process.argv)
//2.根据命令进行操作。。。。。
// 处理 用户 命令 比如: Node-Simple-BFF-Architecture -version
//处理用户命令
const program = require('commander'),
//下载
download = require('download-git-repo'),
//模板引擎当作字符串
handlebars = require('handlebars'),
// 交互
inquirer = require('inquirer'),
//视觉美化
ora = require('ora'),
//字体颜色
chalk = require('chalk'),
//路径
fs = require('fs'),
//对勾优化
logSymbols = require('log-symbols'),
//自定义字符画
chars = [
"",
" ▍ ★∴",
 " s .t .▍▍a...r.█▍ ☆ ★∵t ..../ ",
"  ◥█▅▅██▅▅██▅▅▅▅▅███◤ ",
"   .◥███████████████◤",
"~~~~◥█████████████◤~~~~",
"~~~~~~~~~~~~~~~~~~~~~~~~"
]
//查看版本号
program
.version('1.0.0')
//设计命令 初始化命令
//Node-Simple-BFF-Architecture init node-BFF
program
.command('init <template>')
.description('Initializing BFF architecture')
.action(function(template){
download('https://github.com:1049229070/node-middleware-php#master', template, function (err) {
const spinner = ora(chalk.green('Download in progress...')).start();
if(err){
spinner.fail(chalk.red('Download failed...'));
return false
}
spinner.succeed();
inquirer.prompt([{
type:'input',
name:'name',
message:'Please enter the project name?'
}]).then(answers => {
const packagePath = `${template}/package.json`;
const packageJson = fs.readFileSync(packagePath,'utf-8');
const packageResult = handlebars.compile(packageJson)(answers);
fs.writeFileSync(packagePath,packageResult);
console.log(logSymbols.success,chalk.green(chars.join('\n')))
});
})
});
//设计命令 查看所有帮助
//Node-Simple-BFF-Architecture list
program
.command('list')
.description('View all commands')
.action(function(){
console.log('mode');
})
//设计命令 其他命令处理
program
.command('*')
.action(function(env){
console.log('No operation was found.', env);
});
program.parse(process.argv);
复制代码
七.发布(需要注册一个npm号):
1. npm login
2. npm publish
复制代码
八. 发布过程中遇到的问题。
1. publish Failed PUT 400
复制代码
package.json中name需要小写:
"name": "node-simple-bff-architecture"
复制代码
九. 疑惑。 1.我希望在与用户交互的时候多一些动画效果,不知道有没有大神能给我推荐一些npm包。记得给我流言哦,希望这篇文章对大家理解CLI实际工作原理有用。