欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > nodejs创建文件

nodejs创建文件

2025/5/2 11:44:12 来源:https://blog.csdn.net/Mister_SNAIL/article/details/147413302  浏览:    关键词:nodejs创建文件

环境要求: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


版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词