创建自己的脚手架(二)
接着之前的功能继续开发
脚手架创建组件功能
pnpm add ejs
修改index.js中的文件内容 增加addcpn功能
#!/usr/bin/env node
const { program } = require("commander");
const { addComponentAction, createProjectAction } = require("./core/actions");
const helpOptions = require("./core/help-options");
//1.配置所有的options
helpOptions();
//2.增加具体的一些功能
program
.command("create <project> [...others]")
.description("Create vue project into a folder 比如gucli create xxxx")
.action(createProjectAction);
program
.command("addcpn <cpnname> [...others]")
.description("add vue component into a folder 比如gucli addcpn NavBar -d src/components")
.action(addComponentAction);
//让commander解析process.argv参数
program.parse(process.argv);
//获取额外传递的参数
console.log(program.opts().dest);
具体实行方案写在addComponentAction函数内实现
修改actions.js文件
//promisify将普通函数转换为promise形式
const { promisify } = require("util");
const download = promisify(require("download-git-repo"));
const { VUE_REPO } = require("../config/repo");
const execCommand = require("../utils/exec-command");
const compileEjs = require("../utils/compile-ejs");
const writeFile = require("../utils/write-file");
const { program } = require("commander");
async function createProjectAction(project) {
try {
await download(VUE_REPO, project, { clone: true });
//很多的脚手架 都是在这里提示
//帮助执行npm install
const commandName = process.platform === "win32" ? "npm.cmd" : "npm";
await execCommand(commandName, ["install"], { cwd: `./${project}` });
//帮助执行npm run dev
await execCommand(commandName, ["run", "dev"], { cwd: `./${project}` });
} catch (error) {
console.log("github连接失败");
}
}
async function addComponentAction(cpnname) {
//1.创建一个组件:先编写组件的模板 根据内容给模板添加内容
const result = await compileEjs("component.vue.ejs", {
name: cpnname,
lowername: cpnname.toLowerCase(),
});
//2.将result写入到对应的文件夹中
const dest = program.opts().dest || "src/components";
await writeFile(`${dest}/${cpnname}.vue`, result);
console.log("创建组件成功", cpnname + ".vue");
}
module.exports = {
createProjectAction,
addComponentAction,
};
编写vue组件模板
新建component.vue.ejs文件
<template>
<div class="<%= lowername %>">
<h2><%= name %>:{{ message }}</h2>
</div>
</template>
<script setup>
import { ref } from "vue";
const message = ref("哈哈哈哈");
</script>
<style>
.<%= lowername %> {
color: red;
}
</style>
新建模板编译工具文件compile-ejs.js
const path = require("path");
const ejs = require("ejs");
function compileEjs(tempName, data) {
return new Promise((resolve, reject) => {
//1.获取当前模板的绝对路径
const tempPath = `../template/${tempName}`;
const absolutePath = path.resolve(__dirname, tempPath);
//2.使用ejs引擎编译模板
ejs.renderFile(absolutePath, data, (err, result) => {
if (err) {
console.log("编译模板失败", err);
reject(err);
return;
}
resolve(result);
});
});
}
module.exports = compileEjs;
新建文件流写入文件write-file.js
const fs = require("fs");
function writeFile(path, content) {
return fs.promises.writeFile(path, content);
}
module.exports = writeFile;
然后在终端中输入
gucli addcpn TarBar --dest src/compponents
就会自动创建TarBar.vue组件
整体文件目录