为什么我们需要一套脚手架,它能帮助我们解决哪些痛点问题。
前端项目越来越多,来回下载繁琐、耗时,重复无意义的工作,不方便管理,所以创建一个自己的脚手架非常有必要。 我们可以把远程仓库的项目通过指令来下载项目,没必要再来回下载项目,而且在远程仓库中更方便管理。
创建脚手架项目
npm init -y
脚手架所需要的依赖
"dependencies": {
"commander": "^11.0.0",
"download-git-repo": "^3.0.2",
"inquirer": "^8.2.5",
"ora": "^5.4.1"
}
在package.json文件中配置文件的入口
"bin": {
"uu-cli": "./bin/cli.js"
},
脚手架的初始化
#!/usr/bin/env node
console.log('cli run----');
执行
在使用cli脚手架的时候,可以使用一些命令,如 --version,--help 来查看版本号及帮助信息
// 命令行交互
const program = require('commander')
const package = require('../package.json')
// 定义当前版本
program.version(`v${package.version}`)
// 解析用户执行命令传入参数
program.parse(process.argv)
测试:
在终端输入 npm link 进行导入
使用 uu-cli --version 进行查看版本号
实现创建和选择模板
let templates = [
{
name: 'webpack5-react-ts',
value: 'https://github.com:guojiongwei/webpack5-react-ts'
},
{
name: 'react18-vite2-ts',
value: 'https://github.com:guojiongwei/react18-vite2-ts'
},
{
name: 'dumi2-demo',
value: 'https://github.com:guojiongwei/dumi2-demo'
}
]
program
.command('create')
.description('创建模版')
.action(async () => {
let {name} = await inquirer.prompt({
type:"input",
name:'name',
message:'请输入项目名称:'
})
let { template } = await inquirer.prompt({
type: 'list',
name: 'template',
message: '请选择模版:',
choices: templates // 模版列表
})
console.log('项目名称:',name);
console.log('模版:', template)
// 实现模板下载
const dest = path.join(process.cwd(), name);
downloadGitRepo(template, dest, function (err) {
if (err) {
console.log('下载失败', err)
} else {
console.log('下载成功')
}
})
});
program.parse(process.argv);