84 lines
2.1 KiB
TypeScript
84 lines
2.1 KiB
TypeScript
|
import { Plugin } from 'vite';
|
||
|
import fs from 'fs';
|
||
|
import path from 'path';
|
||
|
|
||
|
/**
|
||
|
* 首字母大写的工具函数
|
||
|
*/
|
||
|
function capitalize(str: string): string {
|
||
|
return str.charAt(0).toUpperCase() + str.slice(1);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 递归扫描目录中的 .vue 文件并生成导出语句
|
||
|
*/
|
||
|
function scanDir(dir: string, baseDir: string): string[] {
|
||
|
const result: string[] = [];
|
||
|
const files = fs.readdirSync(dir);
|
||
|
|
||
|
files.forEach((file) => {
|
||
|
const filePath = path.join(dir, file);
|
||
|
const stat = fs.statSync(filePath);
|
||
|
|
||
|
if (stat.isDirectory()) {
|
||
|
// 递归扫描子目录
|
||
|
result.push(...scanDir(filePath, baseDir));
|
||
|
} else if (file.endsWith('.vue')) {
|
||
|
const relativePath = path.relative(baseDir, filePath);
|
||
|
const componentName = generateComponentName(filePath, baseDir);
|
||
|
result.push(
|
||
|
`export { default as ${componentName} } from './${relativePath.replace(
|
||
|
/\\/g,
|
||
|
'/',
|
||
|
)}';`,
|
||
|
);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 根据文件路径生成组件名
|
||
|
*/
|
||
|
function generateComponentName(filePath: string, baseDir: string): string {
|
||
|
const dirName = path.basename(path.dirname(filePath));
|
||
|
const fileName = path.basename(filePath, '.vue');
|
||
|
|
||
|
if (fileName === 'index') {
|
||
|
return capitalize(dirName);
|
||
|
} else {
|
||
|
return capitalize(fileName);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 插件主逻辑
|
||
|
*/
|
||
|
export default function AutoGenerateVue(options: {
|
||
|
dir: string;
|
||
|
output: string;
|
||
|
}): Plugin {
|
||
|
return {
|
||
|
name: 'vite-plugin-auto-generate-vue',
|
||
|
config() {
|
||
|
const { dir, output } = options;
|
||
|
|
||
|
const componentsDir = path.resolve(process.cwd(), dir);
|
||
|
const outputPath = path.resolve(process.cwd(), output);
|
||
|
|
||
|
if (!fs.existsSync(componentsDir)) {
|
||
|
throw new Error(
|
||
|
`The specified directory "${componentsDir}" does not exist.`,
|
||
|
);
|
||
|
}
|
||
|
|
||
|
const exportStatements = scanDir(componentsDir, componentsDir).join('\n');
|
||
|
|
||
|
// 写入到目标文件
|
||
|
fs.writeFileSync(outputPath, exportStatements, 'utf-8');
|
||
|
console.log(`[autoGenerateVue] Global components written to ${output}`);
|
||
|
},
|
||
|
};
|
||
|
}
|