像咱们熟悉的 vue-cli,react-native-cli 等脚手架,只须要输入简单的命令 vue init webpack project
,便可快速帮咱们生成一个初始项目。在实际工做中,咱们能够定制一个属于本身的脚手架,来提升本身的工做效率。vue
为何须要须要脚手架?node
要开发脚手架,首先要理清思路,脚手架是如何工做的?咱们能够借鉴 vue-cli 的基本思路。vue-cli 是将项目模板放在 git 上,运行的时候再根据用户交互下载不一样的模板,通过模板引擎渲染出来,生成项目。这样将模板和脚手架分离,就能够各自维护,即便模板有变更,只须要上传最新的模板便可,而不须要用户去更新脚手架就能够生成最新的项目。那么就能够按照这个思路来进行开发了。react
首先来看看会用到哪些库。webpack
首先建立一个空项目,暂时命名为 okii-cli,而后新建一个 index.js 文件,再执行 npm init 生成一个 package.json 文件。最后安装上面须要用到的依赖。git
npm install commander download-git-repo inquirer handlebars ora chalk log-symbols -S
node.js 内置了对命令行操做的支持,在 package.json 中的 bin 字段能够定义命令名和关联的执行文件。因此如今 package.json 中加上 bin 的内容:github
{ "name": "okii-cli", "version": "1.0.0", "description": "基于node的脚手架工具", "bin": { "okii": "index.js" }, ... }
而后在 index.js 中来定义 init 命令:web
#!/usr/bin/env node const program = require('commander'); program.version('1.0.0', '-v, --version') .command('init <name>') .action((name) => { console.log(name); }); program.parse(process.argv);
调用 version('1.0.0', '-v, --version')
会将 -v 和 --version 添加到命令中,能够经过这些选项打印出版本号。
调用 command('init <name>')
定义 init 命令,name 则是必传的参数,为项目名。action()
则是执行 init 命令会发生的行为,要生成项目的过程就是在这里面执行的,这里暂时只打印出 name。
其实到这里,已经能够执行 init 命令了。咱们来测试一下,在 okii-cli 的同级目录下执行:vue-cli
node ./okii-cli/index.js init HelloWorld
能够看到命令行工具也打印出了 HelloWorld
,那么很清楚, action((name) => {})
这里的参数 name,就是咱们执行 init 命令时输入的项目名称。shell
命令已经完成,接下来就要下载模板生成项目结构了。npm
download-git-repo 支持从 Github、Gitlab 和 Bitbucket 下载仓库,各自的具体用法能够参考官方文档。
因为是公司项目,因此把模板仓库放在了 Gitlab 上,那么在 action() 中进行操做下载模板:
#!/usr/bin/env node const program = require('commander'); const download = require('download-git-repo'); program.version('1.0.0', '-v, --version') .command('init <name>') .action((name) => { download('http://xxxxxx:9999:HTML5/H5Template#master', name, {clone: true}, (err) => { console.log(err ? 'Error' : 'Success') }) }); program.parse(process.argv);
download()
第一个参数就是仓库地址,可是有一点点不同。实际的仓库地址是 http://xxxxxx:9999/HTML5/H5Template#master ,能够看到端口号后面的 '/' 在参数中要写成 ':',#master 表明的就是分支名,不一样的模板能够放在不一样的分支中,更改分支即可以实现下载不一样的模板文件了。第二个参数是路径,上面咱们直接在当前路径下建立一个 name 的文件夹存放模板,也可使用二级目录好比 test/${name}
命令行交互功能能够在用户执行 init 命令后,向用户提出问题,接收用户的输入并做出相应的处理。这里使用 inquirer.js 来实现。
const inquirer = require('inquirer'); inquirer.prompt([ { type: 'input', name: 'author', message: '请输入做者名称' } ]).then((answers) => { console.log(answers.author); })
经过这里例子能够看出,问题就放在 prompt() 中,问题的类型为 input 就是输入类型,name 就是做为答案对象中的 key,message 就是问题了,用户输入的答案就在 answers 中,使用起来就是这么简单。更多的参数设置能够参考官方文档。
经过命令行交互,得到用户的输入,从而能够把答案渲染到模板中。
这里用 handlebars 的语法对 HTML5/H5Template 仓库的模板中的 package.json 文件作一些修改
{ "name": "{{name}}", "version": "1.0.0", "description": "{{description}}", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "{{author}}", "license": "ISC" }
并在下载模板完成以后将用户输入的答案渲染到 package.json 中
program.version('1.0.0', '-v, --version') .command('init <name>') .action((name) => { inquirer.prompt([ { name: 'description', message: '请输入项目描述' }, { name: 'author', message: '请输入做者名称' } ]).then((answers) => { download('xxxxx#master',name,{clone: true},(err) => { const meta = { name, description: answers.description, author: answers.author } const fileName = `${name}/package.json`; const content = fs.readFileSync(fileName).toString(); const result = handlebars.compile(content)(meta); fs.writeFileSync(fileName, result); }) }) });
这里使用了 node.js 的文件模块 fs,将 handlebars 渲染完后的模板从新写入到文件中。
在用户输入答案以后,开始下载模板,这时候使用 ora 来提示用户正在下载中。
const ora = require('ora'); // 开始下载 const spinner = ora('正在下载模板...'); spinner.start(); // 下载失败调用 spinner.fail(); // 下载成功调用 spinner.succeed();
而后经过 chalk 来为打印信息加上样式,好比成功信息为绿色,失败信息为红色,这样子会让用户更加容易分辨,同时也让终端的显示更加的好看。
const chalk = require('chalk'); console.log(chalk.green('项目建立成功')); console.log(chalk.red('项目建立失败'));
除了给打印信息加上颜色以外,还可使用 log-symbols 在信息前面加上 √ 或 × 等的图标
const chalk = require('chalk'); const symbols = require('log-symbols'); console.log(symbols.success, chalk.green('项目建立成功')); console.log(symbols.error, chalk.red('项目建立失败'));
#!/usr/bin/env node const fs = require('fs'); const program = require('commander'); const download = require('download-git-repo'); const handlebars = require('handlebars'); const inquirer = require('inquirer'); const ora = require('ora'); const chalk = require('chalk'); const symbols = require('log-symbols'); program.version('1.0.0', '-v, --version') .command('init <name>') .action((name) => { if(!fs.existsSync(name)){ inquirer.prompt([ { name: 'description', message: '请输入项目描述' }, { name: 'author', message: '请输入做者名称' } ]).then((answers) => { const spinner = ora('正在下载模板...'); spinner.start(); download('http://xxxxxx:9999:HTML5/H5Template#master', name, {clone: true}, (err) => { if(err){ spinner.fail(); console.log(symbols.error, chalk.red(err)); }else{ spinner.succeed(); const fileName = `${name}/package.json`; const meta = { name, description: answers.description, author: answers.author } if(fs.existsSync(fileName)){ const content = fs.readFileSync(fileName).toString(); const result = handlebars.compile(content)(meta); fs.writeFileSync(fileName, result); } console.log(symbols.success, chalk.green('项目初始化完成')); } }) }) }else{ // 错误提示项目已存在,避免覆盖原有项目 console.log(symbols.error, chalk.red('项目已存在')); } }) program.parse(process.argv);
效果以下:
完成以后,就能够把脚手架发布到 npm 上面,经过 -g 进行全局安装,就能够在本身本机上执行 okii init [name]
来初始化项目,这样便完成了一个简单的脚手架工具了。