ykt-wxapp/scripts/pre-build.js

70 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2026-01-19 18:52:18 +08:00
const fs = require('fs');
const path = require('path');
// 读取 routes 配置并转换为 pages.json
function generatePagesJson() {
// 读取 routes/index.js
const routesPath = path.resolve(__dirname, '../routes/index.js');
if (!fs.existsSync(routesPath)) {
throw new Error('routes/index.js 文件不存在');
}
// 读取文件内容
const fileContent = fs.readFileSync(routesPath, 'utf-8');
// 移除 export default提取数组部分
// 匹配 export default [...] 或 export default [\n...]
const match = fileContent.match(/export\s+default\s+(\[[\s\S]*\])/);
if (!match) {
throw new Error('routes/index.js 格式不正确,无法解析 export default');
}
// 提取数组代码
const routesCode = match[1];
// 使用 Function 构造函数来执行代码并返回数组
const getRoutes = new Function('return ' + routesCode);
const routes = getRoutes();
// 如果 routes 为空,抛出错误
if (!Array.isArray(routes) || routes.length === 0) {
throw new Error('routes/index.js 中必须至少包含一个路由配置');
}
// 读取现有的 pages.json保留其他配置
const pagesJsonPath = path.resolve(__dirname, '../pages.json');
let pagesJson = {
globalStyle: {},
uniIdRouter: {}
};
if (fs.existsSync(pagesJsonPath)) {
const content = fs.readFileSync(pagesJsonPath, 'utf-8');
pagesJson = JSON.parse(content);
}
// 转换 routes 为 pages 格式
const pages = routes.map(route => {
const page = {
path: route.path,
style: {
navigationBarTitleText: route.meta?.title || '',
...(route.style || {})
}
};
return page;
});
// 更新 pages.json保留其他字段
pagesJson.pages = pages;
// 写入文件
fs.writeFileSync(pagesJsonPath, JSON.stringify(pagesJson, null, '\t'), 'utf-8');
console.log('[pre-build] pages.json 已生成');
}
// 执行
console.log('[pre-build] 开始执行预构建脚本...');
generatePagesJson();