工作中打造一款属于自己的命令行工具,很多时候可以很大程度上减少重复工作提高开发效率,简单介绍一下开发一个命令行工具的步骤。
拿快速构建前端项目脚手架为例:
主要开发步骤:
1.创建项目
$ npm init
name: (app-cli)
version: (1.0.0)
description: A command-line tool for creating a custom project
entry point: (index.js)
author:
license: (MIT)
会生成一个package.json文件,在该文件中添加一个bin字段,
bin字段的key就是你的命令,value指向相对于package.json的路径,
不同的key对应不同的命令。关于 bin 字段更多信息请参考 npm 文档中 package.json 一节。
{
"name": "app-cli",
"version": "1.0.0",
"description": "A command-line tool for creating a custom project",
"bin":{
"createApp":"/bin/index.js"
},
"main": "index.js",
"author": "",
"license": "MIT"
}
2.创建bin/index.js文件
#!/usr/bin/env node
console.log('Hello, world!');
注意要添加shebang 来指定脚本运行环境
3.测试
开发时为了方便调试,可以全局执行命令,需要把开发模块镜像到全局,在开发目录中执行命令:
npm link
{userpath}\AppData\Roaming\npm\createapp -> {userpath}\AppData\Roaming\npm\node_modules\app-cli\bin\index.js
{userpath}\AppData\Roaming\npm\node_modules\app-cli -> {userpath}\myproject\app-cli
$ createapp
Hello, world!
这样就可以方便调试代码了。
命令行工具常用模块介绍:
-
Commander.js 命令行交互框架
使用方法:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
2.yargs 另一个命令行交互框架
#!/usr/bin/env node
require('yargs')
.usage('$0 <cmd> [args]')
.command('hello [name]', 'welcome ter yargs!', {
name: {
default: 'default name'
}
}, function (argv) {
console.log('hello', argv.name, 'welcome to yargs!')
})
.help()
.argv
$ node example.js --help
output
test <cmd> [args]
Commands:
hello welcome ter yargs!
Options:
--name, -n provide yer name!
--help Show help
3.Inquirer UI交互就是提示框
var inquirer = require('inquirer');
inquirer.prompt([/* Pass your questions in here */]).then(function (answers) {
// Use user feedback for... whatever!!
});
- Commander.js
- Inquirer.js
- chalk.js
安装使用:
$ npm install app-cli -g
$ createApp
网友评论
E:\my>npm link
npm WARN my@1.0.0 No description
npm WARN my@1.0.0 No repository field.
up to date in 0.071s
npm ERR! path C:\bin\index.js
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall chmod
npm ERR! enoent ENOENT: no such file or directory, chmod 'C:\bin\index.js'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2018-10-12T03_33_35_829Z-debug.log
"createApp":"./bin/index.js"或"createApp":"bin/index.js"成功