背景
在我們?nèi)粘9ぷ髦?,絕非僅僅開發(fā)/維護(hù)單一項(xiàng)目,在新開業(yè)務(wù)線或者新增模塊時(shí)候,通常會(huì)搭建新的項(xiàng)目,雖然現(xiàn)在的vue react 等框架可以快速構(gòu)建一個(gè)基礎(chǔ)項(xiàng)目,但是里面的依賴版本、公共方法,統(tǒng)一規(guī)范等內(nèi)容,還是要從老項(xiàng)目里進(jìn)行copy,有些小伙伴可能會(huì)按照自己的喜好重新封裝,這樣各項(xiàng)目間的規(guī)范,請(qǐng)求方法等并不統(tǒng)一,無(wú)形中增加了后期開發(fā)/維護(hù)的成本,讓大家不能很好的工(滑)作(水)。
我們應(yīng)該將最基礎(chǔ)的規(guī)范、模板等集成到自己的腳手架cli中,這樣只需要一行命令,即可初始化完成一個(gè)符合自己團(tuán)隊(duì)的、具有統(tǒng)一規(guī)范的模板,這樣大家即使維護(hù)不同的項(xiàng)目,也可以愉快的滑水了。
實(shí)現(xiàn)
1、使用commander解析命令行;
2、使用inquirer交互式命令行 ;
3、使用child_process執(zhí)行命令行;
4、使用shelljs監(jiān)聽git命令行狀態(tài);
dome
//xhh-cli.js
const program = require('commander');
const inquirer = require('inquirer');
const { exec } = require("child_process");
const shell = require('shelljs');
const expandReact = [{ name: 'react-router-dom', value: 'react-router-dom' }]
const defaultQuestions = [
// 列表選擇
{
type: 'list',
name: 'template',
message: '請(qǐng)選擇模板',
choices: [{ name: 'react' }, { name: 'vue2' }, { name: 'vue3' }],
},
// 拓展
{
type: 'checkbox',
name: 'expand',
message: '請(qǐng)選擇拓展',
choices: expandReact
},
// 輸入
{
type: 'input',
name: 'appName',
message: '請(qǐng)輸入應(yīng)用名稱',
default() {
return 'project-app';
},
},
];
const questions = [...defaultQuestions];
// 定義程序名稱,版本
program
.name('xhh-cli')
.version('0.0.1')
.action((options, command) => {
inquirer.prompt(questions).then(async (res) => {
exec(`mkdir -p ${res.appName}`, (err) => {
if (!err) {
shell.exec(`git clone xxxx ./${res.appName}`, (code) => {
if (code === 0) {
console.log('====================================');
console.log('初始化成功~');
console.log(`cd ${res.appName}`);
console.log('npm install');
console.log('====================================');
}
})
}
})
});
});
// 解析命令行
program.parse(process.argv);
發(fā)布
/// package.json
"bin": {
"xhh-cli": "bin/xhh-cli.js"
},
通過 npm publish 發(fā)布我們的腳手架包, npm i xhh-cli -g 下載就能用了