@aniyajs/rotor
Version:
基于webpack5开发的一款专注于打包、运行的工具
124 lines (100 loc) • 2.87 kB
JavaScript
const path = require("path");
const paths = require("./paths");
const fs = require("fs-extra");
const memFs = require("mem-fs");
const editor = require("mem-fs-editor");
const ejs = require("ejs");
const { aRecursive } = require("./common");
class PluginGenerator {
constructor(args) {
this.describeParams = {};
// 插件包node_modules中入口地址
this.pluginIndex = args.pluginIndex;
// app config配置
this.configition = args.config;
this.resolve = path.resolve;
this.join = path.join;
this.relative = path.relative;
this.basename = path.basename;
this.editorFs = null;
}
initialize() {
// 清空一次插件生成的缓存文件
this.clearAllTemp();
const store = memFs.create();
const editorFs = editor.create(store);
this.editorFs = editorFs;
}
use(plugin) {
plugin(this);
}
/**
* 描述插件
*/
describe(params) {
this.describeParams = {
...params,
};
}
/**
* 插件生成
*/
generate(onGenerateHandle) {
const parentDirPath = path.dirname(this.pluginIndex);
const parentFileName = path.basename(parentDirPath);
const pluginTempPath = path.join(paths.appTempPath, parentFileName);
onGenerateHandle({
pluginTempPath, // 插件生成的缓存目录地址
...paths,
});
}
// 异步读取当前目录下过滤后的是否携带后缀的文件
async readFilterdir({ rootPath, withSuffix, filterHandle }) {
const files = await aRecursive(rootPath);
const specifyFiles = files.filter(filterHandle).map((filePath) => {
// 为true时获取文件后缀
if (withSuffix) {
return filePath;
}
// 解析文件路径
const parsedPath = path.parse(filePath);
// 获取不带文件后缀的路径
const directoryPath = parsedPath.dir;
const fileName = parsedPath.name;
const pathWithoutExtension = path.join(directoryPath, fileName);
return pathWithoutExtension;
});
return specifyFiles;
}
// 同步复制模板
copyTpl(from, to, define) {
// 自定义 ejs 模版文件后缀名
ejs.extname = path.extname(from);
if (fs.existsSync(to)) {
fs.removeSync(to);
}
this.editorFs.copyTpl(from, to, define);
this.editorFs.commit(() => {});
}
// 同步写入方法
writeFile(config) {
const { file, content } = config;
if (fs.existsSync(file)) {
fs.removeSync(file);
}
this.editorFs.write(file, content);
this.editorFs.commit(() => {});
}
// 清除所有缓存文件
clearAllTemp() {
const files = fs.readdirSync(paths.appTempPath);
files.forEach((file) => {
if (file.startsWith("plugin-")) {
fs.removeSync(path.join(paths.appTempPath, file));
}
});
}
// 结束
ending() {}
}
module.exports = PluginGenerator;