环境要求:nodejs
运行命令:
node createComponent.js
各文件内容:
createComponent.js
/*
* 功能概述:
* 1. 通过命令行交互,用户输入组件名称,选择模板类型。
* 2. 根据用户输入生成对应的Vue组件、Service类文件。
* 3. 将组件配置添加到componentConfig.json文件中。
*/
// 引入依赖模块
const kebabCase = require('lodash/kebabCase'); // 将字符串转换为中划线命名
require('colors'); // 为控制台输出添加颜色
const path = require('path'); // 处理文件路径
const fileSave = require('file-save'); // 用于保存文件(也可以使用Node.js的内置文件模块fs来实现)
const readlineSync = require('readline-sync'); // 用于命令行交互(也可以使用Node.js的内置模块readline来实现)
// 监听进程退出事件
process.on('exit', () => {
console.log('exit'); // 输出退出信息
});
// 用户输入组件名称
const componentName = readlineSync.question('Please Input Your ComponentName: '.blue); // 提示用户输入组件名称
const type = readlineSync.keyInSelect([
'a-document'.yellow,
'b-document'.yellow,
], 'Please Choose Template Type: '.blue); // 提示用户选择模板类型
// 检查必填项
if (!componentName) {
console.error('[组件名]必填'.red); // 如果组件名称为空,提示错误并退出
process.exit(1); // 状态码1表示程序异常退出,明确标识错误退出
}
// 定义文件路径
const folderName = kebabCase(componentName); // 将组件名称转换为中划线命名
const PackagePath = path.resolve(__dirname, `../src/views/`); // Vue组件存放路径
const servicePackagePath = path.resolve(__dirname, `../src/api/${folderName}/`); // Service类存放路径
// 定义要创建的文件内容
const Files = [
{
packagePath: PackagePath,
filename: `${componentName}.vue`, // Vue组件文件名
content: `<script>
import ${componentName}Service from '@/api/${folderName}/${componentName}Service';
export default {
data() {
return {
service: new ${componentName}Service(),
};
},
};
</script>` // Vue组件内容
}, {
packagePath: servicePackagePath,
filename: `${componentName}Service.js`, // Service类文件名
content: `class ${componentName}Service {}
export default ${componentName}Service;` // Service类内容
}
];
// 处理子表单配置
const componentConfig= require('../src/views/componentConfig.json'); // 加载子表单配置文件
// 检查组件是否已存在
if (componentConfig[componentName]) {
console.error(`组件 ${componentName} 已存在,请检查后重新输入.`.red); // 如果组件已存在,提示错误并退出
process.exit(1); // 状态码1表示程序异常退出,明确标识错误退出
}
// 定义模板类型
const types = ['a-document', 'b-document', 'c-document'];
// 更新组件配置
componentConfig[componentName] = {
"type": types[type] ?? "c-document", // 根据用户选择的模板类型设置默认值
};
// 保存更新后的组件配置文件
fileSave(path.join(__dirname, '../src/views/componentConfig.json'))
.write(JSON.stringify(componentConfig, null, 2), 'utf8') // 将 configFile 对象转换为格式化的 JSON 字符串,缩进为两个空格
.end('\n');
// 创建文件
Files.forEach(file => {
fileSave(path.join(file.packagePath, file.filename))
.write(file.content, 'utf8') // 写入文件内容
.end('\n');
});
console.log('DONE!'.green); // 输出完成信息
componentConfig.json