const fs = require('fs'); const path = require('path'); // 读取映射文件 const mappingPath = path.join(__dirname, 'homework_poster_mapping.json'); const posterMapping = JSON.parse(fs.readFileSync(mappingPath, 'utf-8')); console.log('已加载 ' + Object.keys(posterMapping).length + ' 个课程海报映射'); // 读取mockData.js文件 const mockDataPath = path.join(__dirname, 'src/data/mockData.js'); let mockDataContent = fs.readFileSync(mockDataPath, 'utf-8'); // 找到homework数组的开始位置 const homeworkStartMatch = mockDataContent.match(/homework:\s*\[/); if (!homeworkStartMatch) { console.error('无法找到homework数组!'); process.exit(1); } // 使用正则表达式来匹配和替换课程对象 // 匹配格式: { id: X, name: "课程名", level: "xxx", ...其他字段 } const coursePattern = /\{\s*id:\s*(\d+),\s*name:\s*"([^"]+)",\s*level:\s*"([^"]+)"(\s*,\s*isShowCase:\s*(true|false))?\s*\}/g; let updatedCount = 0; let notFoundCourses = []; mockDataContent = mockDataContent.replace(coursePattern, (match, id, name, level, showCaseGroup, isShowCase) => { const imageUrl = posterMapping[name]; if (imageUrl) { updatedCount++; // 构建新的课程对象字符串 let newCourse = `{ id: ${id}, name: "${name}", level: "${level}", imageUrl: "${imageUrl}"`; if (showCaseGroup) { newCourse += `, isShowCase: ${isShowCase}`; } newCourse += ' }'; return newCourse; } else { notFoundCourses.push(name); return match; // 保持原样 } }); // 保存更新后的文件 fs.writeFileSync(mockDataPath, mockDataContent, 'utf-8'); console.log('\n✅ 更新完成!'); console.log('更新了 ' + updatedCount + ' 个课程的图片URL'); if (notFoundCourses.length > 0) { console.log('\n⚠️ 以下 ' + notFoundCourses.length + ' 个课程没有找到对应的海报图片:'); notFoundCourses.forEach(name => console.log(' - ' + name)); } else { console.log('\n🎉 所有课程都成功匹配到海报图片!'); }