UNPKG

kunkun-cli

Version:

109 lines (101 loc) 2.68 kB
const { getRepoList } = require('./http') const ora = require('ora') const inquirer = require('inquirer') const downloadGitRepo = require('download-git-repo') const util = require('util') const path = require('path') class Generator { constructor(name, targetDir) { // 框架名称 this.frameworkList = [ { name: 'Vue2', value: 'vue2' }, { name: 'Vue3', value: 'vue3' }, { name: 'React', value: 'react' } ] // 模板、自定义 this.selectList = [ { name: '模板创建', value: 'template' }, { name: '自定义', value: 'custom' } ] // 模板 this.repoList = [] // 目录名称 this.name = name // 创建位置 this.targetDir = targetDir // 对down-git-repo进行promise化改造 this.downloadGitRepo = util.promisify(downloadGitRepo) } // 选择型交互 async selectPrompt(choices, message) { const { sel } = await inquirer.prompt({ name: 'sel', type: 'list', choices, message }) return sel } // 从远程获取模板数据 async getList() { this.repoList = await wrapLoading(getRepoList, '获取模板中...') } // 选择模板 async selectTem(framework) { // 过滤模板名称 const repos = this.repoList.filter(item => item.description === framework).map(item => item.name) // 用户自行选择模板 return this.selectPrompt(repos, '请选择一个模板来创建项目') } // 下载远程模板 async download(repo) { // 拼接下载地址 const requestUrl = `kunkun-cli-template/${repo}` // 调用下载方法 await wrapLoading( this.downloadGitRepo, '下载模板中', requestUrl, path.resolve(process.cwd(), this.targetDir) ) } // 创建逻辑 async create() { const framework = await this.selectPrompt(this.frameworkList, '请选择框架') const type = await this.selectPrompt(this.selectList, '请选择创建方式') if(type === 'template') { await this.getList() const repo = await this.selectTem(framework) console.log('用户选择了:', repo); await this.download(repo) } } } // 添加加载动画 async function wrapLoading(fn, message, ...args) { const spinner = ora(message) spinner.start() try { const result = await fn(...args) spinner.succeed() return result } catch (error) { spinner.fail('获取模板失败') } } module.exports = Generator