搭建一个nodejs脚手架的方法步骤

2020-06-17 05:58:16易采站长站整理


npm install --save commander

引入 commander 我们将 index.js 做如下修改


#!/usr/bin/env node

console.log('Hello, cli!')

const program = require('commander')
program
.version(require('./package').version, '-v, --version')
.command('init <name>')
.action((name) => {
console.log(name)
})

program.parse(process.argv)

可以通过 lq -v 来查看版本号 通过 lq init name 的操作,action里面会打印出name

2.2.3 对console的美工

我们看到taro init 命令里面会有一些颜色标识,就是因为引入了chalk这个包,同样和 commander 一样


npm install --save chalk

console.log(chalk.green(‘init创建’))

这样会输出一样绿色的

2.2.4 模板下载

download-git-repo 支持从 Github下载仓库,详细了解可以参考官方文档。


npm install --save download-git-repo

download() 第一个参数就是仓库地址,详细了解可以看官方文档

2.2.5 命令行的交互

命令行交互功能可以在用户执行 init 命令后,向用户提出问题,接收用户的输入并作出相应的处理。用 inquirer.js 来实现。


npm install --save inquirer

index.js文件如下


#!/usr/bin/env node
const chalk = require('chalk')
console.log('Hello, cli!')
console.log(chalk.green('init创建'))
const program = require('commander')
const download = require('download-git-repo')
const inquirer = require('inquirer')
program
.version(require('./package').version, '-v, --version')
.command('init <name>')
.action((name) => {
console.log(name)
inquirer.prompt([
{
type: 'input',
name: 'author',
message: '请输入你的名字'
}
]).then((answers) => {
console.log(answers.author)
download('',
name, {clone: true}, (err) => {
console.log(err ? 'Error' : 'Success')
})
})

})
program.parse(process.argv)

2.2.6 ora进度显示


npm install --save ora

相关命令可以如下


const ora = require('ora')
// 开始下载
const proce = ora('正在下载模板...')
proce.start()

// 下载失败调用
proce.fail()

// 下载成功调用
proce.succeed()

2.2.6 log-symbols 在信息前面加上 √ 或 × 等的图标


npm install --save log-symbols

相关命令可以如下