const fs = require('fs');
|
const path = require('path');
|
|
// 1. 配置源代码目录和输出目录
|
const SOURCE_DIR = path.resolve(__dirname, './src/example/');
|
const OUTPUT_DIR = path.resolve(__dirname, './public/example/');
|
|
// 2. 递归查找所有以 Page.js 结尾的文件
|
function findPageJsFiles(dir) {
|
const files = fs.readdirSync(dir);
|
let pageJsFiles = [];
|
|
files.forEach(file => {
|
const fullPath = path.join(dir, file);
|
const stat = fs.statSync(fullPath);
|
|
if (stat.isDirectory()) {
|
// 如果是目录,递归查找
|
pageJsFiles = pageJsFiles.concat(findPageJsFiles(fullPath));
|
} else if (file.endsWith('Page.js') && file !== 'ExamplePage.js') {
|
// 如果是 Page.js 文件,添加到结果中
|
pageJsFiles.push(fullPath);
|
}
|
});
|
|
return pageJsFiles;
|
}
|
|
// 3. 生成 Markdown 内容
|
function generateMarkdown(code, filePath) {
|
const fileName = path.basename(filePath, '.js');
|
return `
|
### ${fileName} 代码
|
|
\`\`\`jsx
|
${code}
|
\`\`\`
|
`;
|
}
|
|
// 4. 主函数
|
function main() {
|
// 确保输出目录存在
|
if (!fs.existsSync(OUTPUT_DIR)) {
|
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
|
}
|
|
// 查找所有 Page.js 文件
|
const pageJsFiles = findPageJsFiles(SOURCE_DIR);
|
|
if (pageJsFiles.length === 0) {
|
console.log('⚠️ 未找到任何以 Page.js 结尾的文件');
|
return;
|
}
|
|
console.log(`🔍 找到 ${pageJsFiles.length} 个 Page.js 文件:`);
|
pageJsFiles.forEach(file => console.log(` - ${file}`));
|
|
// 处理每个文件
|
pageJsFiles.forEach(filePath => {
|
try {
|
// 读取源代码
|
const code = fs.readFileSync(filePath, 'utf8');
|
|
// 生成 Markdown 内容
|
const mdContent = generateMarkdown(code, filePath);
|
|
// 确定输出路径(保持相对路径结构)
|
const relativePath = path.relative(SOURCE_DIR, filePath);
|
const outputFilePath = path.join(OUTPUT_DIR, relativePath.replace(/\.js$/, '.md'));
|
|
// 确保输出目录存在
|
const outputDir = path.dirname(outputFilePath);
|
if (!fs.existsSync(outputDir)) {
|
fs.mkdirSync(outputDir, { recursive: true });
|
}
|
|
// 写入 Markdown 文件
|
fs.writeFileSync(outputFilePath, mdContent);
|
|
console.log(`✅ 已生成: ${outputFilePath}`);
|
} catch (error) {
|
console.error(`❌ 处理文件 ${filePath} 时出错:`, error.message);
|
}
|
});
|
}
|
|
// 执行主函数
|
main();
|