2025-12-17 18:27:59 +08:00
|
|
|
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('</template>');
|
|
|
|
|
if (lastTemplateEndIndex !== -1) {
|
|
|
|
|
const newCode =
|
|
|
|
|
code.slice(0, lastTemplateEndIndex) +
|
|
|
|
|
'\n <global-popup />\n' +
|
|
|
|
|
code.slice(lastTemplateEndIndex);
|
|
|
|
|
|
2025-12-17 19:48:45 +08:00
|
|
|
console.log(`[精准注入]: ${relativePath}`);
|
2025-12-17 18:27:59 +08:00
|
|
|
return {
|
|
|
|
|
code: newCode,
|
|
|
|
|
map: null
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|