readline-vue2-cli
Version:
一个 mini 版的自定义脚手架
89 lines (75 loc) • 2.81 kB
JavaScript
/*
* @Author: wjl
* @Date: 2023-02-27 08:51:49
* @LastEditors: wjl
* @LastEditTime: 2023-03-02 10:35:28
* @FilePath: \re-build-cli\bin\generator.js
*/
const path = require('path');
const fs = require('fs-extra');
// 引入ora工具:命令行loading 动效
const ora = require('ora');
const inquirer = require('inquirer');
// 引入download-git-repo工具
const downloadGitRepo = require('download-git-repo');
// download-git-repo 默认不支持异步调用,需要使用util插件的util.promisify 进行转换
const util = require('util');
//引入克隆工具
const clone = require('git-clone');
//引入删除工具
const rm = require("rimraf").sync;
// 获取项目目标目录
const { sourceUrl } = require('./http');
// 创建项目类
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);
}
// 下载项目模板
download() {
return new Promise((resolve, reject) => {
const spinner = ora('waiting download template');
// 下载开始
spinner.start();
fs.copy(sourceUrl, path.resolve(process.cwd(), this.target), err => {
if (err) {
spinner.fail('completed download template');
return reject()
}
spinner.succeed('completed download template');
resolve()
})
})
}
// 文件入口,在create.js中 执行generator.create();
async create() {
// 下载用户选择的项目模板
await this.download();
// 下载完成后,获取项目里的package.json并删除本地连接git库连接
// 将用户创建项目的填写的信息(项目名称、作者名字、描述),写入到package.json中
let targetPath = path.resolve(process.cwd(), this.target);
let jsonPath = path.join(targetPath, 'package.json');
let gitPath = path.join(`${targetPath}\\.git`);
rm(gitPath)
if (fs.existsSync(jsonPath)) {
// 读取已下载模板中package.json的内容
const data = fs.readFileSync(jsonPath).toString();
let json = JSON.parse(data);
json.name = this.name;
// 让用户输入的内容 替换到 package.json中对应的字段
Object.keys(this.ask).forEach((item) => {
json[item] = this.ask[item];
});
//修改项目文件夹中 package.json 文件
fs.writeFileSync(jsonPath, JSON.stringify(json, null, '\t'), 'utf-8');
}
}
}
module.exports = Generator;