UNPKG

gxm-build-cli

Version:

一个mini版的脚手架

124 lines (76 loc) 2.78 kB
const path = require('path') const fs= require('fs-extra') // 命令行loading const ora = require('ora') const inquirer = require('inquirer') // git-repo工具 const downloadGitRepo = require('download-git-repo') // download-git-repo 默认不支持异步调用,需要使用util插件的util.promisify 进行转换 const util = require('util'); // 获取git项目列表 const { getRepolist } = require('./http'); 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('请求失败'); } } class Generator { // name 项目名称 // target 创建项目的路径 // 用户输入的 作者和项目描述 信息 constructor(name, target, ask) { this.name = name this.target = target this.ask = ask // download-git-repo 默认不支持异步调用,需要使用util插件的util.promisify 进行转换 this.downloadGitRepo = util.promisify(downloadGitRepo); } async getRepo() { // 获取git项目列表 const repolist = await wrapLoading(getRepolist, '正在拉取模板'); if(!repolist) return const repos = repolist.map(item => item.name) // 让用户选择要下载的模板 const {repo} = await inquirer.prompt({ name: 'repo', type: 'list', choices: repos, message: '请选择模板' }) return repo } async download(repo,tag) { const requestUrl = `yuan-cli/${repo}` await wrapLoading(this.downloadGitRepo, '等待下载模板', requestUrl, path.resolve(process.cwd(), this.target)) } async create() { const repo = await this.getRepo(); console.log('用户选择了', repo); // 下载用户选择的模板 await this.download(repo) // 下载完后,获取项目里的package.json // 将用户创建项目的填写的信息(项目名称、作者名字、描述),写入到package.json中 const targetPath = path.resolve(process.cwd(), this.target); const jsonPath = path.join(targetPath, 'package.json'); if(fs.existsSync(jsonPath)) { // 读取已下载模板中的package.json的内容 const data = fs.readFileSync(jsonPath).toString() const json = JSON.parse(data) json.name = this.name // 用户输入的内容替换 Object.keys(this.ask).forEach(item => { json[item] = this.ask[item]; }) // 重新写回去 fs.writeFileSync(jsonPath, JSON.stringify(json, null, '\t'), 'utf-8') } } } module.exports = Generator