新建文件夹 template-cli
template-cli下运行
npm init
生成package.json
新建bin文件夹和index.js文件
编写index.js
#! /usr/bin/env node
console.log('hello cli')
package.json增加 bin 字段注册命令template-cli
template-cli
命令对应执行的内容文件 bin/index.js
运行 npm link,就可以把template-cli
注册到命令行
npm link
测试一下,运行自己的命令template-cli
,输出了index.js中编写的内容 hello cli
继续编写更多内容使用 commander
包
我们来安装下
npm install commander --save
考虑使用 ESModule模块编写,所以在package.json文件中配置 "type": "module"
使用commander编写index.js
import { Command } from 'commander'
const program = new Command()
program.name('create template').description('Use template-cli to create').version('0.0.1')
program.parse()
现在我们可以使用 --help
和 --version
来获取我们的描述信息和版本信息
下面我们要编写一些真正的执行事项
program.command('create <name>').description('create a new project').action(async (name) => {console.log(name)})
program.parse()
运行create命令得到的输出
目前为止,index.js中的全部内容如下
#! /usr/bin/env node
console.log('hello cli')
import { Command } from 'commander'
const program = new Command()
program.name('create template').description('Use template-cli to create').version('0.0.1')
program.command('create <name>').description('create a new project').action(async (name) => {console.log(name)})
program.parse()
运行不带任务的命令结果如下