import fs from 'fs'; import path from 'path'; // 读取并解析 pages.json function getPagesConfig() { const pagesJsonPath = path.resolve(__dirname, 'pages.json'); let rawContent = fs.readFileSync(pagesJsonPath, 'utf8'); // 核心修复:使用正则去除 JSON 中的 // 和 /* */ 注释 const jsonContent = rawContent.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, ""); const pagesJson = JSON.parse(jsonContent); const pagePaths = []; // 1. 提取主包页面 if (pagesJson.pages) { pagesJson.pages.forEach(p => pagePaths.push(p.path)); } // 2. 提取分包页面 if (pagesJson.subPackages) { pagesJson.subPackages.forEach(sub => { if (sub.pages) { sub.pages.forEach(p => { pagePaths.push(`${sub.root}/${p.path}`); }); } }); } return pagePaths; } const allPages = getPagesConfig(); export default function viteInjectPopup() { return { name: 'vite-inject-popup', enforce: 'pre', transform(code, id) { // 将绝对路径转为相对项目的路径,便于匹配 // 例如: /Users/.../pages/index/index.vue -> pages/index/index const relativePath = id.replace(/\\/g, '/').split('.vue')[0]; // 校验当前文件是否在 pages.json 的定义中 const isTargetPage = allPages.some(pagePath => relativePath.endsWith(pagePath)); if (isTargetPage && !code.includes('global-popup')) { const lastTemplateEndIndex = code.lastIndexOf(''); if (lastTemplateEndIndex !== -1) { const newCode = code.slice(0, lastTemplateEndIndex) + '\n \n' + code.slice(lastTemplateEndIndex); console.log(`[精准注入]: ${relativePath}`); return { code: newCode, map: null }; } } return null; } }; }