相信很多前端都听说过或者使用过@angular/cli, vue-cli, create-react-app或其他类似的命令行工具。他们能够在命令行后面跟各种复杂的参数已经交互性的命令行选项,那你知道这些功能是怎么实现的吗?
Commander.js
node.js命令行开发工具开发库,使node.js开发CLI工具变得简单,允许快捷的定义形如<command> [options]的命令。
基础用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const program = require('commander');
program .version(require('../package.json').version, '-v, --version') .usage('<command> [options]'); program .command('rm <dir>') .description('删除文件或文件夹') .option('-r, --recursive', 'Remove recursively') .action(function (dir, cmd) { console.log('remove ' + dir + (cmd.recursive ? ' recursively' : '')) }); program.parse(process.argv);
|
github仓库:https://github.com/tj/commander.js
Inquirer.js
node.js 交互式命令行界面开发库,允许方便的定义使用上下左右进行列表选择等交互式命令。
基础用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const inquirer = require('inquirer');
inquirer.prompt( { type: 'input', name: 'name', message: '请输入项目名称', default: 'unnamed' validate: (input: string) => { if (input.length > 255) { return '项目名称超过限制'; } return true; } }, { type: 'list', name: 'type', message: '请选择', choices: ['item1', 'item2', 'item3', 'item4'], default: 'project' }).then(answers => { console.log(answers.name); console.log(answers.type); });
|
github仓库:https://github.com/SBoudrias/Inquirer.js
Ora
优雅的命令行Loading动画。
1 2 3 4 5 6 7 8 9 10 11 12
| const ora = require('ora');
const spinner = ora('Loading unicorns').start();
setTimeout(() => { spinner.color = 'yellow'; spinner.text = 'Loading rainbows'; }, 1000);
setTimeout(() => { spinner.stop(); }, 2000);
|
github仓库:https://github.com/sindresorhus/ora
Chalk
给命令行输出的文本添加样式
1 2 3 4 5 6 7 8 9 10 11
| const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
console.log(chalk.blue('Hello') + ' World' + chalk.red('!'));
console.log(chalk.blue.bgRed.bold('Hello world!'));
|
github仓库:https://github.com/chalk/chalk