添加脚本
在操作组件库的时候有一些操作比较繁琐,因此添加脚本,通过脚本执行这些繁琐的事情
在项目根目录创建script目录
添加组件
创建组件目录及固定结构
每次新建组件都需要徐建如下操作:
- 在packages文件夹中创建组件目录
- 在docs\demos中创建组件的目录
- 在docs\components中创建组件目录
- ……
通过编写一些脚本帮我自动创建对应的文件夹和文件,在script目录创建add.js和tools.js文件以及创建add文件夹,在add文件夹下创建directoryfile.js文件
:::demo
${componentname}/index
:::
`;
// 文档目录
const directory = path.join(docpath, componentname);
// 判断是否有工具路径
const isexists = fs.existssync(directory);
if (isexists) {
exit(`${directory}目录已经存在`);
}
// 文档路径
const documentpath = path.join(directory, "/base.md");
fs.mkdirsync(directory);
// 写入文件
fs.writefilesync(documentpath, documenttemplate); // 工具
mylog("创建组件文档", documentpath);
// ------- 创建组件文档 end ------
// ---------创建组件demo start -----
// demo路径
const demopath = path.join(__dirname, "../../docs/demos");
// demo目录
const demodirectory = path.join(demopath, componentname);
// 创建文件夹
fs.mkdirsync(demodirectory);
// 文件路径
const demofilepath = path.join(demodirectory, "/index.vue");
// demo 模板
const demotemplate = `<template>
<div>
<${capitalizefirstletter(componentname)} />
</div>
</template>
<script>
export default {
name: "${componentname}-demo",
};
</script>
<style lang="scss" scoped>
</style>`;
// 写入文件
fs.writefilesync(demofilepath, demotemplate); // 工具
mylog("创建demo文件", demofilepath);
// ---------创建组件demo end -----
// ---------创建组件 start -----
// 组件路径
const componentpath = path.join(__dirname, "../../packages");
// 组件目录
const componentdirectory = path.join(componentpath, componentname);
// 创建文件夹
fs.mkdirsync(componentdirectory);
// 组件主目录
const componentmaindirectory = path.join(componentdirectory, "src");
// 创建文件夹
fs.mkdirsync(componentmaindirectory);
// 组件主文件
const componentmainfilepath = path.join(componentmaindirectory, "/index.vue");
// 组件内容
const componenttemplate = `<template>
<div>
<div>${componentname}</div>
</div>
</template>
<script>
export default {
name: "${componentname}",
};
</script>
<style lang="scss" scoped>
</style>`;
fs.writefilesync(componentmainfilepath, componenttemplate);
// 组件安装文件
const componentinstallpath = path.join(componentdirectory, "index.ts");
// 判断导入组件组件组件使用大写还是小写
let subassembly =
capitalizefirstletter(componentname) === componentname
? lowerfirstletter(componentname)
: capitalizefirstletter(componentname);
// 组件安装
const componentinstall = `import ${subassembly} from "./src/index.vue";
import { withinstall } from "../withinstall";
const ${capitalizefirstletter(componentname)} = withinstall(${subassembly});
export default ${capitalizefirstletter(componentname)};`;
// 写入文件
fs.writefilesync(componentinstallpath, componentinstall);
mylog("创建组件目录", componentdirectory);
// ---------创建组件 end -----
};组件介绍
:::demo
${componentname}/index
:::
`;
// 文档目录
const directory = path.join(docpath, componentname);
// 判断是否有工具路径
const isexists = fs.existssync(directory);
if (isexists) {
exit(`${directory}目录已经存在`);
}
// 文档路径
const documentpath = path.join(directory, "/base.md");
fs.mkdirsync(directory);
// 写入文件
fs.writefilesync(documentpath, documenttemplate); // 工具
mylog("创建组件文档", documentpath);
// ------- 创建组件文档 end ------
// ---------创建组件demo start -----
// demo路径
const demopath = path.join(__dirname, "../../docs/demos");
// demo目录
const demodirectory = path.join(demopath, componentname);
// 创建文件夹
fs.mkdirsync(demodirectory);
// 文件路径
const demofilepath = path.join(demodirectory, "/index.vue");
// demo 模板
const demotemplate = `<template>
<div>
<${capitalizefirstletter(componentname)} />
</div>
</template>
<script>
export default {
name: "${componentname}-demo",
};
</script>
<style lang="scss" scoped>
</style>`;
// 写入文件
fs.writefilesync(demofilepath, demotemplate); // 工具
mylog("创建demo文件", demofilepath);
// ---------创建组件demo end -----
// ---------创建组件 start -----
// 组件路径
const componentpath = path.join(__dirname, "../../packages");
// 组件目录
const componentdirectory = path.join(componentpath, componentname);
// 创建文件夹
fs.mkdirsync(componentdirectory);
// 组件主目录
const componentmaindirectory = path.join(componentdirectory, "src");
// 创建文件夹
fs.mkdirsync(componentmaindirectory);
// 组件主文件
const componentmainfilepath = path.join(componentmaindirectory, "/index.vue");
// 组件内容
const componenttemplate = `<template>
<div>
<div>${componentname}</div>
</div>
</template>
<script>
export default {
name: "${componentname}",
};
</script>
<style lang="scss" scoped>
</style>`;
fs.writefilesync(componentmainfilepath, componenttemplate);
// 组件安装文件
const componentinstallpath = path.join(componentdirectory, "index.ts");
// 判断导入组件组件组件使用大写还是小写
let subassembly =
capitalizefirstletter(componentname) === componentname
? lowerfirstletter(componentname)
: capitalizefirstletter(componentname);
// 组件安装
const componentinstall = `import ${subassembly} from "./src/index.vue";
import { withinstall } from "../withinstall";
const ${capitalizefirstletter(componentname)} = withinstall(${subassembly});
export default ${capitalizefirstletter(componentname)};`;
// 写入文件
fs.writefilesync(componentinstallpath, componentinstall);
mylog("创建组件目录", componentdirectory);
// ---------创建组件 end -----
};在add.js导入
/* eslint-disable no-undef */
import { warn } from "./tools.js";
import { directoryfile } from "./add/directoryfile.js";
// 组件名称
let componentname = process.argv[2];
if (!componentname) {
warn("usage: npm run add <component-name>");
process.exit(1);
}
// 创建目录
directoryfile();然后在package.json中添加命令就可以了
"add": "node ./script/add.js"
这样需要创建组件的时候只需要在命令行中输入
npm run add 组件名称
修改components.d.ts
上面的操作创建了组件的目录及基本结构,在创建组件的时候还需要再components.d.ts引入组件设置类型
因此在add文件夹下面创建add-componentdts.js文件,并在add.js中引入
/* eslint-disable no-undef */
// 添加 packages\components.d.ts 文件中的类型
import fs from "fs-extra";
import { mylog, capitalizefirstletter } from "../tools.js";
const componentname = process.argv[2]; // 从命令行参数获取组件名
// 需要处理的文件路径
const filepath = "./packages/components.d.ts"; // 文件路径,请替换为实际路径
// 需要导入的组件路径
const importpath = `./${componentname.tolowercase()}/src/index.vue`; // 假设组件的导入路径与组件名相关联
// 导入组件
const importstatement = `import ${capitalizefirstletter(componentname)} from "${importpath}";\n`;
// 组件类型
const componentdeclaration = `\t${capitalizefirstletter(componentname)}: typeof ${capitalizefirstletter(componentname)};\n`;
async function addcomponent() {
try {
let filecontent = await fs.readfile(filepath, "utf8");
// 检查是否已存在该组件的导入和声明,避免重复添加
if (!filecontent.includes(importstatement) && !filecontent.includes(componentdeclaration)) {
// 在导入部分添加新组件导入
// eslint-disable-next-line quotes
const importsectionendindex = filecontent.indexof('declare module "vue"');
filecontent =
filecontent.slice(0, importsectionendindex) +
importstatement +
filecontent.slice(importsectionendindex);
// 在globalcomponents接口中添加新组件声明
const globalcomponentsstartindex = filecontent.indexof("{", importsectionendindex);
const globalcomponentsendindex = filecontent.indexof("}", importsectionendindex);
// 提取出 导出的类型
const globalcomponentssection = filecontent.slice(
globalcomponentsstartindex,
globalcomponentsendindex,
);
filecontent = filecontent.replace(
globalcomponentssection,
`${globalcomponentssection}${componentdeclaration}`,
);
await fs.writefile(filepath, filecontent, "utf8");
// console.log(`component ${componentname} has been added successfully.`);
mylog(`component ${componentname} has been added successfully.`);
} else {
// console.log(`component ${componentname} is already present in the file.`);
mylog(`component ${componentname} is already present in the file.`);
}
} catch (error) {
console.error("an error occurred:", error);
}
}
export default addcomponent;修改index.ts
在add文件夹下面创建add-indexts.js文件
/* eslint-disable no-undef */
import fs from "fs";
import { mylog, capitalizefirstletter } from "../tools.js";
// 指定要修改的文件路径
const filepath = "./packages/index.ts"; // 要添加的组件名称
const componentname = process.argv[process.argv.length - 1]; // 从命令行参数获取,如 'abc'
// 确保组件名符合导入语句的格式
const formattedcomponentname = componentname.replace(/\.vue$/, "").replace(/^\//, "");
export const addindexts = () => {
// 读取文件内容
fs.readfile(filepath, "utf8", (err, data) => {
if (err) {
console.error(`读取文件失败: ${err}`);
return;
}
// 添加导入语句在现有导入语句之后(如果尚未存在)
const importregex = /import\s+.+?from\s+["'].*?["'];/g;
let lastimportmatch;
while ((lastimportmatch = importregex.exec(data)) !== null) {
// 找到最后一个匹配的导入语句
}
const importline = `\nimport ${capitalizefirstletter(formattedcomponentname)} from "./${formattedcomponentname}";\n`;
if (!lastimportmatch || !data.includes(importline)) {
const insertposition = lastimportmatch
? lastimportmatch.index + lastimportmatch[0].length
: data.indexof("const components:");
data = data.slice(0, insertposition) + importline + data.slice(insertposition);
}
// 更新组件列表(如果尚未存在)
const componentsstart = "const components: { [propname: string]: component } = {";
const componentsend = "};";
const componentsindexstart = data.indexof(componentsstart);
const componentsindexend = data.indexof(componentsend, componentsindexstart);
if (componentsindexstart !== -1 && componentsindexend !== -1) {
let componentsblock = data.substring(
componentsindexstart,
componentsindexend + componentsend.length,
);
if (!componentsblock.includes(`${formattedcomponentname}:`)) {
componentsblock = componentsblock.replace(
componentsend,
` ${capitalizefirstletter(formattedcomponentname)},\n${componentsend}`,
);
data =
data.substring(0, componentsindexstart) +
componentsblock +
data.substring(componentsindexend + componentsend.length);
}
}
// 更新导出语句
const exportstart = "export {";
const exportend = "};";
const exportindexstart = data.lastindexof(exportstart);
const exportindexend = data.indexof(exportend, exportindexstart);
if (exportindexstart !== -1 && exportindexend !== -1) {
let exportsblock = data.substring(exportindexstart, exportindexend + exportend.length);
if (!exportsblock.includes(`${formattedcomponentname},`)) {
const currentexports = exportsblock
.replace(exportstart, "")
.replace(exportend, "")
.trim()
.split(",")
.map(s => s.trim());
if (currentexports[currentexports.length - 1] !== "") {
currentexports.push(capitalizefirstletter(formattedcomponentname));
exportsblock = `${exportstart} ${currentexports.join(", ")} ${exportend}`;
} else {
exportsblock = exportsblock.replace(
exportend,
`, ${formattedcomponentname}\n${exportend}`,
);
}
data =
data.substring(0, exportindexstart) +
exportsblock +
data.substring(exportindexend + exportend.length);
}
}
// 写回文件
fs.writefile(filepath, data, "utf8", err => {
if (err) {
console.error(`写入文件失败: ${err}`);
} else {
mylog(`${formattedcomponentname} 已成功添加到文件`, "packages/index.ts");
}
});
});
};添加vitepress菜单
经过以上操作添加组件基本完成,还剩余添加说明文档的侧边栏
在add文件夹中创建add-vitepressconfig.js
/* eslint-disable no-undef */
import fs from "fs";
import { mylog } from "../tools.js";
const vitepressconfig = "./docs/.vitepress/config.ts";
const componentname = process.argv[2]; // 从命令行参数获取,如 'abc'
const componentnamecn = process.argv[3]; // 从命令行参数获取,如 'abc'
const addmenu = `{ text: "${componentnamecn || "组件名称"}", link: "/components/${componentname}/base.md" },`;
export const addvitepressconfig = () => {
// 读取文件
fs.readfile(vitepressconfig, "utf8", (err, data) => {
if (err) {
console.error(`读取文件失败: ${err}`);
return;
}
let componentsindexstart = data.indexof("items: [");
let componentsend = "],";
let componentsindexend = data.indexof(componentsend, componentsindexstart);
let componentsblock = data.substring(componentsindexstart, componentsindexend);
componentsblock = `
${componentsblock}
${addmenu}
`;
data =
data.substring(0, componentsindexstart) +
componentsblock +
data.substring(componentsindexend);
fs.writefile(vitepressconfig, data, "utf8", err => {
if (err) {
console.error(`写入文件失败: ${err}`);
} else {
mylog(
`${componentnamecn || "组件"}${componentname} 已成功添加到文档库菜单`,
"docs/.vitepress/config.ts",
);
}
});
});
};使用
经过以上完成了组件创建脚本,这样就不需要我们自己在修改一些文件了,直接编写组件内容、demo、组件文档就可以了
在命令行中使用
npm run add table 表格
- table 是组件的文件夹名称和组件的name名称
- 表格 用来在说明文档中展示和菜单显示
组件名称首字母无论是大写还是小写字母,在使用的时候都需要使用的时候都需要变成大写字母
提交git
每次需要提交代码的时候都需要执行git add . 、git commit -m "" 、git push
编写一个脚本帮我们自动提交代码
安装依赖
npm i child_process -d
在script文件夹下面创建push.js
/* eslint-disable no-undef */
// 导入node.js的child_process模块中的exec函数,用于在子进程中执行shell命令
import { exec } from "child_process";
import { finish, warn } from "./tools.js";
// 这个异步函数接收一个命令字符串作为参数,使用exec执行该命令,并将其包装成一个promise。如果命令执行成功,它会解析promise并返回包含stdout和stderr的对象;如果执行失败,则拒绝promise并返回错误。
const runcommand = command =>
new promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
reject(error);
} else {
resolve({ stdout, stderr });
}
});
});
// 这是一个异步函数,负责执行一系列git操作:添加所有改动、根据提供的或默认的提交信息进行提交、然后推送更改。它接受一个可选的commitmessage参数,默认值为"新增组件"。
const main = async (commitmessage = "新增组件") => {
try {
await runcommand("git add .");
const messageoption = commitmessage ? `-m "${commitmessage}"` : "";
await runcommand(`git commit ${messageoption}`);
await runcommand("git push");
finish("代码提交成功");
} catch (error) {
warn("error during git operations:", error);
}
};
// 从命令行参数读取提交信息
// 从node.js进程的命令行参数中读取信息。process.argv是一个数组,包含了启动脚本的node.js可执行文件的路径、脚本文件的路径,以及之后的所有参数。slice(2)用来去掉前两个元素,只保留实际传入的参数。如果提供了参数,它们会被连接成一个字符串作为提交信息,否则使用默认的"新增组件"。
const args = process.argv.slice(2);
const commitmessage = args.length > 0 ? args.join(" ") : "新增组件";
// 调用main函数,并使用.catch处理任何在执行过程中抛出的错误,错误信息会被打印到控制台。
main(commitmessage).catch(console.error);打包部署
对项目进行打包部署分为如下几步:
- 更改版本号
- 打包npm
- 切换镜像源
- 登录镜像源
- 部署
在script文件夹下卖弄创建npmpush.js和npmpush文件夹
更改版本号
在npmpush文件夹下面创建bumpversion.js
// 修改版本号
import fs from "fs";
import path from "path";
import { fileurltopath } from "url";
import { finish, warn } from "../tools.js";
export const bumpversion = () => {
// 当前文件路径
const __filename = fileurltopath(import.meta.url);
// 当前文件的目录
const __dirname = path.dirname(__filename);
// 读取package.json文件
const packagepath = path.resolve(__dirname, "../../package.json");
const packagejson = json.parse(fs.readfilesync(packagepath, "utf8"));
// 原来的版本
const originally = packagejson.version;
// 分解版本号为数组,便于操作
const versionparts = packagejson.version.split(".").map(number);
// 示例:递增补丁版本号
versionparts[2]++; // 假设是主版本.次版本.补丁版本的形式
// 重新组合版本号
packagejson.version = versionparts.join(".");
// 将修改后的内容写回package.json
fs.writefilesync(packagepath, json.stringify(packagejson, null, 2), "utf8");
finish(`版本更新成功: ${originally} --> ${packagejson.version}`, packagepath);
};在script\npmpush.js文件中引入
import { bumpversion } from "./npmpush/bumpversion.js";
bumpversion();打包组件库
在npmpush文件夹下面创建packnpm.js
/* eslint-disable no-undef */
// 导入node.js的child_process模块中的exec函数,用于在子进程中执行shell命令
import { finish, warn, runcommand } from "../tools.js";
export const packnpm = async () => {
// 这是一个异步函数,负责执行一系列git操作:添加所有改动、根据提供的或默认的提交信息进行提交、然后推送更改。它接受一个可选的commitmessage参数,默认值为"新增组件"。
try {
await runcommand("npm run lib");
finish("打包成功");
} catch (error) {
warn("打包发生错误:", error);
}
};在script\npmpush.js文件中引入
import { bumpversion } from "./npmpush/bumpversion.js";
import { packnpm } from "./npmpush/packnpm.js";
const npmpush = async () => {
await bumpversion();
await packnpm();
};
npmpush();提交npm私库
在npmpush文件夹下面创建submitnpm.js
/* eslint-disable no-undef */
import { finish, warn, runcommand } from "../tools.js";
export const submitnpm = async () => {
try {
await runcommand("npm publish");
finish("推送成功");
await runcommand("npm run push '部署' ");
finish("代码提交成功");
} catch (error) {
warn("打包发生错误:", error);
}
};在script\npmpush.js文件中引入
import { bumpversion } from "./npmpush/bumpversion.js";
import { packnpm } from "./npmpush/packnpm.js";
import { submitnpm } from "./npmpush/submitnpm.js";
const npmpush = async () => {
await bumpversion();
await packnpm();
await submitnpm();
};
npmpush();总结
暂时先添加这三个脚本吧,需要注意的是:在打包部署之前需要登录npm库
在代码中用到的tools.js文件
/* eslint-disable no-undef */
// 导入node.js的child_process模块中的exec函数,用于在子进程中执行shell命令
import { exec } from "child_process";
import ora from "ora";
// 首字母大写
export const capitalizefirstletter = str => str.charat(0).touppercase() + str.slice(1);
// 首字母转小写
export const lowerfirstletter = str => str.charat(0).tolowercase() + str.slice(1);
// 打印
// 打印方法
export const mylog = function (text, path) {
/* var black="\033[30m black \033[0m";
var red="\033[31m red \033[0m";
var green="\033[32m green \033[0m";
var yellow="\033[33m yellow78979 \033[0m";
var blue="\033[34m blue \033[0m";
var popurse="\033[35m popurse \033[0m";
var indigo="\033[36m indigo \033[0m";
var white="\033[37m white \033[0m";
var mix="\033[37;42m white \033[0m";
console.log(black, red, green, yellow, blue, popurse, white);*/
let popurse = "\x1b[32m 提示 \x1b[0m";
process.stdout.write(popurse);
let toolpathhint = "\x1b[34m " + text + " \x1b[0m";
let toolpathpath = "\x1b[32m" + path + " \x1b[0m";
console.log(toolpathhint, toolpathpath);
};
export const warn = function (text) {
/* var black="\033[30m black \033[0m";
var red="\033[31m red \033[0m";
var green="\033[32m green \033[0m";
var yellow="\033[33m yellow78979 \033[0m";
var blue="\033[34m blue \033[0m";
var popurse="\033[35m popurse \033[0m";
var indigo="\033[36m indigo \033[0m";
var white="\033[37m white \033[0m";
var mix="\033[37;42m white \033[0m";
console.log(black, red, green, yellow, blue, popurse, white);*/
let popurse = "\x1b[31m 警告 \x1b[0m";
process.stdout.write(popurse);
let toolpathhint = "\x1b[31m " + text + " \x1b[0m";
console.log(toolpathhint);
};
/**
*
* @param {string} text 输出打印
*/
export const finish = function (text) {
/* var black="\033[30m black \033[0m";
var red="\033[31m red \033[0m";
var green="\033[32m green \033[0m";
var yellow="\033[33m yellow78979 \033[0m";
var blue="\033[34m blue \033[0m";
var popurse="\033[35m popurse \033[0m";
var indigo="\033[36m indigo \033[0m";
var white="\033[37m white \033[0m";
var mix="\033[37;42m white \033[0m";
console.log(black, red, green, yellow, blue, popurse, white);*/
let popurse = "\x1b[35m 完成 \x1b[0m";
process.stdout.write(popurse);
let toolpathhint = "\x1b[36m " + text + " \x1b[0m";
console.log(toolpathhint);
};
/**
*
* @param {string} command 需要执行的命令
* @returns
*/
export const runcommand = command => {
let isgit = command.indexof("git") === -1;
let spinner;
if (isgit) {
spinner = ora(`开始执行: "${command}"`).start();
}
return new promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
mylog("\n当前命令:", command);
if (error) {
if (isgit) {
spinner.fail(`exec error: ${error}`);
}
reject("error", error);
} else {
if (isgit) {
// 打印命令的标准输出和标准错误,如果需要的话
if (command === "npm run lib") {
// spinner.succeed(`命令 "${command}" 执行成功.`);
console.log(`命令输出: ${stdout}`);
console.error(`stderr: ${stderr}`);
finish("打包完成");
} else if (command === "git push") {
finish("代码提交成功");
} else if (command === "npm publish") {
finish("npm库推送成功");
}
spinner.succeed(`命令 "${command}" 执行成功.`);
resolve(true); // 命令成功执行, 解决promise
} else {
resolve({ stdout, stderr });
}
}
});
});
};
到此这篇关于vue3组件库添加脚本的实现示例的文章就介绍到这了,更多相关vue3组件库添加脚本内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论