完善生产查询与登录权限配置
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
# vite-plugin-uni-root
|
||||
|
||||
UniApp 虚拟根组件 Vite 插件,零额外依赖,纯字符串操作实现。
|
||||
|
||||
## 解决的问题
|
||||
|
||||
UniApp 不支持原生的根组件包裹机制,无法在全局统一注入 `u-config-provider`、`u-toast`、`u-modal` 等需要在每个页面根部存在的组件。传统方案需要在每个页面手动添加,维护成本高。
|
||||
|
||||
本插件通过 Vite 构建时注入,自动为每个页面包裹 `<global-root-view>` 根组件,无需修改任何页面代码本身。
|
||||
|
||||
## 技术方案
|
||||
|
||||
### 架构
|
||||
|
||||
```
|
||||
App.root.vue(源码) → 在 main.ts 中导入并注册为全局组件 global-root-view
|
||||
→ 页面模板被包裹 <global-root-view> 页面内容 </global-root-view>
|
||||
→ 渲染时页面内容填入 <slot />
|
||||
```
|
||||
|
||||
### 工作流程
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌──────────────┐ ┌─────────────────┐
|
||||
│ main.ts │ → │ 注入 import │ → │ 全局注册组件 │
|
||||
│ │ │ + 注册代码 │ │ global-root-view │
|
||||
└─────────────┘ └──────────────┘ └─────────────────┘
|
||||
│
|
||||
┌─────────────┐ ┌──────────────┐ │
|
||||
│ page.vue │ → │ 包裹模板 │ │
|
||||
│ │ │ <global-...> │ ←─────────┘
|
||||
└─────────────┘ └──────────────┘
|
||||
│
|
||||
┌─────────────┐ │
|
||||
│ App.root.vue│ → <slot /> 接收页面内容
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
### 三步实现
|
||||
|
||||
1. **main.ts 注入**(`root.ts -> registerRootApp`)
|
||||
- 在 main.ts 中注入 `import GlobalRootView from "./App.root.vue"`
|
||||
- 注入 `app.component("global-root-view", GlobalRootView)` 注册为全局组件
|
||||
- 注:`GlobalRootView` 仅为局部变量名,实际组件就是 `App.root.vue`
|
||||
|
||||
2. **页面模板包裹**(`page.ts -> transformPage`)
|
||||
- 解析 SFC,定位 `<template>` 标签的起止位置
|
||||
- 提取 PageMeta 节点(如有则放到包裹层外部)
|
||||
- 将模板内容包裹在 `<global-root-view>...</global-root-view>` 中
|
||||
|
||||
3. **App.root.vue 加载**(`index.ts -> load`)
|
||||
- 拦截 `App.root.vue` 的模块请求,从文件读取并返回
|
||||
- 模板中的 `<slot />` 接收并渲染页面内容
|
||||
|
||||
### 跨端兼容
|
||||
|
||||
插件是纯 Vite 构建时插件,在 UniApp 编译之前完成源代码转换,不依赖任何平台特定 API,所有 UniApp 支持的平台均可正常工作:
|
||||
|
||||
| 平台 | 支持 |
|
||||
|------|------|
|
||||
| H5 | ✅ |
|
||||
| 微信小程序 | ✅ |
|
||||
| 支付宝小程序 | ✅ |
|
||||
| 头条/抖音小程序 | ✅ |
|
||||
| Android App | ✅ |
|
||||
| iOS App | ✅ |
|
||||
| 鸿蒙 App | ✅ |
|
||||
|
||||
## 使用方式
|
||||
|
||||
### 1. 创建 App.root.vue
|
||||
|
||||
在 `src/` 目录下创建 `App.root.vue` 文件:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { onLoad } from '@dcloudio/uni-app';
|
||||
import { useTheme, useLocale } from 'uview-pro';
|
||||
|
||||
const { darkMode, themes, currentTheme } = useTheme();
|
||||
const { currentLocale } = useLocale();
|
||||
|
||||
onLoad(() => {
|
||||
console.log('darkMode->', darkMode.value);
|
||||
console.log('theme->', currentTheme.value?.name);
|
||||
console.log('locale->', currentLocale.value?.name);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<u-config-provider
|
||||
:dark-mode="darkMode"
|
||||
:themes="themes"
|
||||
:current-theme="currentTheme?.name"
|
||||
:current-locale="currentLocale?.name"
|
||||
>
|
||||
<slot />
|
||||
<u-toast global></u-toast>
|
||||
<u-modal global></u-modal>
|
||||
</u-config-provider>
|
||||
</template>
|
||||
```
|
||||
|
||||
关键点:`<slot />` 是页面内容的渲染位置,必须保留。
|
||||
|
||||
### 2. 配置 vite.config.ts
|
||||
|
||||
```ts
|
||||
// npm 安装
|
||||
import { UniRoot } from 'uview-pro/plugins';
|
||||
|
||||
// uni_modules 安装
|
||||
import { UniRoot } from './src/uni_modules/uview-pro/plugins';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
UniRoot(), // 放在其他插件之前
|
||||
// ...其他插件
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### 3. 运行
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
不需要修改任何页面代码,所有页面自动被 `<global-root-view>` 包裹。
|
||||
|
||||
## 文件结构
|
||||
|
||||
```
|
||||
src/uni_modules/uview-pro/plugins/root/
|
||||
├── index.ts # 插件入口,Vite 插件生命周期
|
||||
├── root.ts # main.ts 注入 + App.root.vue 处理
|
||||
├── page.ts # 页面模板包裹转换
|
||||
└── utils.ts # 工具函数(SFC 解析、pages.json 加载、AST 查找等)
|
||||
```
|
||||
|
||||
## 配置项
|
||||
|
||||
```ts
|
||||
UniRoot({
|
||||
rootFileName: 'App.root', // 根组件文件名(不含扩展名),默认 App.root
|
||||
})
|
||||
```
|
||||
|
||||
## HMR 支持
|
||||
|
||||
修改 `pages.json` 后自动重载页面列表,无需手动重启开发服务器。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- Vue 版本需 >= 3.2.13(使用 `vue/compiler-sfc` 的 `parse` API,HBuilderX 环境下自动降级为正则匹配)
|
||||
- 页面模板中如有 `<page-meta>` 组件,会被提取到包裹层外部,确保微信小程序兼容
|
||||
- 页面模板中如有嵌套 `<template #slot>` 具名插槽,不影响根模板的正确识别
|
||||
|
||||
## 致谢
|
||||
|
||||
本插件的实现参考了 [@uni-ku/root](https://github.com/uni-ku/root)(MIT License,作者 skiyee),核心思路受其启发并进行了重新实现。
|
||||
@@ -0,0 +1,111 @@
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var root_exports = {};
|
||||
__export(root_exports, {
|
||||
UniRoot: () => UniRoot,
|
||||
default: () => root_default
|
||||
});
|
||||
module.exports = __toCommonJS(root_exports);
|
||||
var import_node_path = require("node:path");
|
||||
var import_node_process = __toESM(require("node:process"));
|
||||
var import_node_fs = require("node:fs");
|
||||
var import_vite = require("vite");
|
||||
var import_root = require("./root.cjs");
|
||||
var import_page = require("./page.cjs");
|
||||
var import_utils = require("./utils.cjs");
|
||||
function normalizeId(id) {
|
||||
return (0, import_vite.normalizePath)(id).replace(/^[A-Z]:/, (match) => match.toLowerCase());
|
||||
}
|
||||
function UniRoot(options) {
|
||||
options = {
|
||||
rootFileName: "App.root",
|
||||
...options
|
||||
};
|
||||
const rootPath = import_node_process.default.env.UNI_INPUT_DIR || (0, import_node_path.join)(import_node_process.default.cwd(), "src");
|
||||
const appRootPath = (0, import_node_path.resolve)(rootPath, `${options.rootFileName}.vue`);
|
||||
const pagesPath = (0, import_node_path.resolve)(rootPath, "pages.json");
|
||||
let pagesJson = (0, import_utils.loadPagesJson)(pagesPath, rootPath);
|
||||
let watcher = null;
|
||||
let hasPlatformPlugin = false;
|
||||
const normalizedAppRoot = normalizeId(appRootPath);
|
||||
return {
|
||||
name: "vite-plugin-uni-root",
|
||||
enforce: "pre",
|
||||
// 在其他插件之前执行,确保页面模板先被包裹
|
||||
configResolved({ plugins }) {
|
||||
hasPlatformPlugin = plugins.some((v) => v.name === "vite-plugin-uni-platform");
|
||||
},
|
||||
configureServer(server) {
|
||||
const reload = (0, import_utils.debounce)(() => {
|
||||
try {
|
||||
pagesJson = (0, import_utils.loadPagesJson)(pagesPath, rootPath);
|
||||
server.ws.send({ type: "full-reload" });
|
||||
} catch (e) {
|
||||
console.error("[vite-plugin-uni-root] pages.json reload failed:", e);
|
||||
}
|
||||
}, 100);
|
||||
watcher = (0, import_node_fs.watch)(pagesPath, (eventType) => {
|
||||
if (eventType === "change")
|
||||
reload();
|
||||
});
|
||||
},
|
||||
load(id) {
|
||||
const normalizedId = normalizeId(id);
|
||||
if (normalizedId === normalizedAppRoot) {
|
||||
const code = (0, import_node_fs.readFileSync)(appRootPath, "utf-8");
|
||||
return (0, import_root.rebuildRootApp)(code).code;
|
||||
}
|
||||
},
|
||||
async transform(code, id) {
|
||||
const normalizedId = normalizeId(id);
|
||||
const normalizedRootPath = normalizeId(rootPath);
|
||||
if (normalizedId === `${normalizedRootPath}/main.ts` || normalizedId === `${normalizedRootPath}/main.js`) {
|
||||
return (0, import_root.registerRootApp)(code, options.rootFileName);
|
||||
}
|
||||
if (normalizedId === normalizedAppRoot) {
|
||||
return (0, import_root.rebuildRootApp)(code);
|
||||
}
|
||||
const pageId = hasPlatformPlugin ? (0, import_utils.normalizePlatformPath)(normalizedId) : normalizedId;
|
||||
const isPage = pagesJson.some((p) => pageId === p || pageId.startsWith(`${p}?`));
|
||||
if (isPage) {
|
||||
return (0, import_page.transformPage)(code);
|
||||
}
|
||||
},
|
||||
buildEnd() {
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
watcher = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
var root_default = UniRoot;
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
UniRoot
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { resolve, join } from "node:path";
|
||||
import process from "node:process";
|
||||
import { watch, readFileSync } from "node:fs";
|
||||
import { normalizePath } from "vite";
|
||||
import { registerRootApp, rebuildRootApp } from "./root.mjs";
|
||||
import { transformPage } from "./page.mjs";
|
||||
import { loadPagesJson, normalizePlatformPath, debounce } from "./utils.mjs";
|
||||
function normalizeId(id) {
|
||||
return normalizePath(id).replace(/^[A-Z]:/, (match) => match.toLowerCase());
|
||||
}
|
||||
function UniRoot(options) {
|
||||
options = {
|
||||
rootFileName: "App.root",
|
||||
...options
|
||||
};
|
||||
const rootPath = process.env.UNI_INPUT_DIR || join(process.cwd(), "src");
|
||||
const appRootPath = resolve(rootPath, `${options.rootFileName}.vue`);
|
||||
const pagesPath = resolve(rootPath, "pages.json");
|
||||
let pagesJson = loadPagesJson(pagesPath, rootPath);
|
||||
let watcher = null;
|
||||
let hasPlatformPlugin = false;
|
||||
const normalizedAppRoot = normalizeId(appRootPath);
|
||||
return {
|
||||
name: "vite-plugin-uni-root",
|
||||
enforce: "pre",
|
||||
// 在其他插件之前执行,确保页面模板先被包裹
|
||||
configResolved({ plugins }) {
|
||||
hasPlatformPlugin = plugins.some((v) => v.name === "vite-plugin-uni-platform");
|
||||
},
|
||||
configureServer(server) {
|
||||
const reload = debounce(() => {
|
||||
try {
|
||||
pagesJson = loadPagesJson(pagesPath, rootPath);
|
||||
server.ws.send({ type: "full-reload" });
|
||||
} catch (e) {
|
||||
console.error("[vite-plugin-uni-root] pages.json reload failed:", e);
|
||||
}
|
||||
}, 100);
|
||||
watcher = watch(pagesPath, (eventType) => {
|
||||
if (eventType === "change")
|
||||
reload();
|
||||
});
|
||||
},
|
||||
load(id) {
|
||||
const normalizedId = normalizeId(id);
|
||||
if (normalizedId === normalizedAppRoot) {
|
||||
const code = readFileSync(appRootPath, "utf-8");
|
||||
return rebuildRootApp(code).code;
|
||||
}
|
||||
},
|
||||
async transform(code, id) {
|
||||
const normalizedId = normalizeId(id);
|
||||
const normalizedRootPath = normalizeId(rootPath);
|
||||
if (normalizedId === `${normalizedRootPath}/main.ts` || normalizedId === `${normalizedRootPath}/main.js`) {
|
||||
return registerRootApp(code, options.rootFileName);
|
||||
}
|
||||
if (normalizedId === normalizedAppRoot) {
|
||||
return rebuildRootApp(code);
|
||||
}
|
||||
const pageId = hasPlatformPlugin ? normalizePlatformPath(normalizedId) : normalizedId;
|
||||
const isPage = pagesJson.some((p) => pageId === p || pageId.startsWith(`${p}?`));
|
||||
if (isPage) {
|
||||
return transformPage(code);
|
||||
}
|
||||
},
|
||||
buildEnd() {
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
watcher = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
var root_default = UniRoot;
|
||||
export {
|
||||
UniRoot,
|
||||
root_default as default
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var page_exports = {};
|
||||
__export(page_exports, {
|
||||
transformPage: () => transformPage
|
||||
});
|
||||
module.exports = __toCommonJS(page_exports);
|
||||
var import_utils = require("./utils.cjs");
|
||||
async function transformPage(code) {
|
||||
const sfc = await (0, import_utils.parseSFC)(code);
|
||||
const openMatch = code.match(/<template\b[^>]*>/);
|
||||
if (!openMatch)
|
||||
return null;
|
||||
const closeTagStart = code.lastIndexOf("</template>");
|
||||
if (closeTagStart === -1)
|
||||
return null;
|
||||
const openTagEnd = openMatch.index + openMatch[0].length;
|
||||
const content = code.slice(openTagEnd, closeTagStart);
|
||||
let pageMetaSource = "";
|
||||
let newContent = content;
|
||||
if (sfc == null ? void 0 : sfc.template) {
|
||||
const pageMetaNode = (0, import_utils.findNode)(sfc, "PageMeta");
|
||||
if (pageMetaNode) {
|
||||
pageMetaSource = pageMetaNode.loc.source;
|
||||
const metaStart = pageMetaNode.loc.start.offset;
|
||||
const metaEnd = pageMetaNode.loc.end.offset;
|
||||
const metaStartInContent = metaStart - openTagEnd;
|
||||
const metaEndInContent = metaEnd - openTagEnd;
|
||||
newContent = content.slice(0, metaStartInContent) + content.slice(metaEndInContent);
|
||||
}
|
||||
} else {
|
||||
const pageMetaMatch = content.match(/<page-meta\b[^>]*>[\s\S]*?<\/page-meta>/);
|
||||
if (pageMetaMatch) {
|
||||
pageMetaSource = pageMetaMatch[0];
|
||||
newContent = content.replace(pageMetaMatch[0], "");
|
||||
} else {
|
||||
const selfClosingMatch = content.match(/<page-meta\b[^>]*\/>/);
|
||||
if (selfClosingMatch) {
|
||||
pageMetaSource = selfClosingMatch[0];
|
||||
newContent = content.replace(selfClosingMatch[0], "");
|
||||
}
|
||||
}
|
||||
}
|
||||
const wrappedContent = `
|
||||
${pageMetaSource}
|
||||
<global-root-view>${newContent}</global-root-view>
|
||||
`;
|
||||
return {
|
||||
code: code.slice(0, openTagEnd) + wrappedContent + code.slice(closeTagStart),
|
||||
map: {
|
||||
version: 3,
|
||||
sources: [],
|
||||
names: [],
|
||||
mappings: ""
|
||||
}
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
transformPage
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { parseSFC, findNode } from "./utils.mjs";
|
||||
async function transformPage(code) {
|
||||
const sfc = await parseSFC(code);
|
||||
const openMatch = code.match(/<template\b[^>]*>/);
|
||||
if (!openMatch)
|
||||
return null;
|
||||
const closeTagStart = code.lastIndexOf("</template>");
|
||||
if (closeTagStart === -1)
|
||||
return null;
|
||||
const openTagEnd = openMatch.index + openMatch[0].length;
|
||||
const content = code.slice(openTagEnd, closeTagStart);
|
||||
let pageMetaSource = "";
|
||||
let newContent = content;
|
||||
if (sfc == null ? void 0 : sfc.template) {
|
||||
const pageMetaNode = findNode(sfc, "PageMeta");
|
||||
if (pageMetaNode) {
|
||||
pageMetaSource = pageMetaNode.loc.source;
|
||||
const metaStart = pageMetaNode.loc.start.offset;
|
||||
const metaEnd = pageMetaNode.loc.end.offset;
|
||||
const metaStartInContent = metaStart - openTagEnd;
|
||||
const metaEndInContent = metaEnd - openTagEnd;
|
||||
newContent = content.slice(0, metaStartInContent) + content.slice(metaEndInContent);
|
||||
}
|
||||
} else {
|
||||
const pageMetaMatch = content.match(/<page-meta\b[^>]*>[\s\S]*?<\/page-meta>/);
|
||||
if (pageMetaMatch) {
|
||||
pageMetaSource = pageMetaMatch[0];
|
||||
newContent = content.replace(pageMetaMatch[0], "");
|
||||
} else {
|
||||
const selfClosingMatch = content.match(/<page-meta\b[^>]*\/>/);
|
||||
if (selfClosingMatch) {
|
||||
pageMetaSource = selfClosingMatch[0];
|
||||
newContent = content.replace(selfClosingMatch[0], "");
|
||||
}
|
||||
}
|
||||
}
|
||||
const wrappedContent = `
|
||||
${pageMetaSource}
|
||||
<global-root-view>${newContent}</global-root-view>
|
||||
`;
|
||||
return {
|
||||
code: code.slice(0, openTagEnd) + wrappedContent + code.slice(closeTagStart),
|
||||
map: {
|
||||
version: 3,
|
||||
sources: [],
|
||||
names: [],
|
||||
mappings: ""
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
transformPage
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var root_exports = {};
|
||||
__export(root_exports, {
|
||||
rebuildRootApp: () => rebuildRootApp,
|
||||
registerRootApp: () => registerRootApp
|
||||
});
|
||||
module.exports = __toCommonJS(root_exports);
|
||||
function createEmptySourcemap() {
|
||||
return {
|
||||
version: 3,
|
||||
sources: [],
|
||||
names: [],
|
||||
mappings: ""
|
||||
};
|
||||
}
|
||||
function registerRootApp(code, fileName = "App.root") {
|
||||
const importCode = `import GlobalRootView from "./${fileName}.vue";`;
|
||||
const vueUseComponentCode = `app.component("global-root-view", GlobalRootView);`;
|
||||
let newCode = importCode + "\n" + code;
|
||||
const ssrAppMatch = newCode.match(/(const\s+app\s*=\s*createSSRApp\([^)]+\);)/);
|
||||
if (ssrAppMatch) {
|
||||
newCode = newCode.replace(/(const\s+app\s*=\s*createSSRApp\([^)]+\);)/, `$1
|
||||
${vueUseComponentCode}`);
|
||||
} else {
|
||||
newCode = newCode.replace(/(createApp[\s\S]*?)(return\s*\{)/, `$1${vueUseComponentCode}
|
||||
$2`);
|
||||
}
|
||||
return { code: newCode, map: createEmptySourcemap() };
|
||||
}
|
||||
function rebuildRootApp(code) {
|
||||
return { code, map: createEmptySourcemap() };
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
rebuildRootApp,
|
||||
registerRootApp
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
function createEmptySourcemap() {
|
||||
return {
|
||||
version: 3,
|
||||
sources: [],
|
||||
names: [],
|
||||
mappings: ""
|
||||
};
|
||||
}
|
||||
function registerRootApp(code, fileName = "App.root") {
|
||||
const importCode = `import GlobalRootView from "./${fileName}.vue";`;
|
||||
const vueUseComponentCode = `app.component("global-root-view", GlobalRootView);`;
|
||||
let newCode = importCode + "\n" + code;
|
||||
const ssrAppMatch = newCode.match(/(const\s+app\s*=\s*createSSRApp\([^)]+\);)/);
|
||||
if (ssrAppMatch) {
|
||||
newCode = newCode.replace(/(const\s+app\s*=\s*createSSRApp\([^)]+\);)/, `$1
|
||||
${vueUseComponentCode}`);
|
||||
} else {
|
||||
newCode = newCode.replace(/(createApp[\s\S]*?)(return\s*\{)/, `$1${vueUseComponentCode}
|
||||
$2`);
|
||||
}
|
||||
return { code: newCode, map: createEmptySourcemap() };
|
||||
}
|
||||
function rebuildRootApp(code) {
|
||||
return { code, map: createEmptySourcemap() };
|
||||
}
|
||||
export {
|
||||
rebuildRootApp,
|
||||
registerRootApp
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var utils_exports = {};
|
||||
__export(utils_exports, {
|
||||
debounce: () => debounce,
|
||||
findNode: () => findNode,
|
||||
formatPagePath: () => formatPagePath,
|
||||
loadPagesJson: () => loadPagesJson,
|
||||
normalizePlatformPath: () => normalizePlatformPath,
|
||||
parseSFC: () => parseSFC,
|
||||
stripJsonComments: () => stripJsonComments,
|
||||
toKebabCase: () => toKebabCase,
|
||||
toPascalCase: () => toPascalCase
|
||||
});
|
||||
module.exports = __toCommonJS(utils_exports);
|
||||
var import_node_fs = require("node:fs");
|
||||
var import_node_path = require("node:path");
|
||||
var import_vite = require("vite");
|
||||
async function parseSFC(code) {
|
||||
try {
|
||||
const { parse } = await import("vue/compiler-sfc");
|
||||
return parse(code, { pad: "space" }).descriptor;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function stripJsonComments(str) {
|
||||
return str.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
}
|
||||
function formatPagePath(root, path) {
|
||||
return (0, import_vite.normalizePath)(`${(0, import_node_path.join)(root, path)}.vue`).replace(/^[A-Z]:/, (match) => match.toLowerCase());
|
||||
}
|
||||
function loadPagesJson(path, rootPath) {
|
||||
const raw = (0, import_node_fs.readFileSync)(path, "utf-8");
|
||||
const { pages = [], subPackages = [] } = JSON.parse(stripJsonComments(raw));
|
||||
return [
|
||||
...pages.map((page) => formatPagePath(rootPath, page.path)),
|
||||
...subPackages.map(({ pages: subPages = [], root = "" }) => {
|
||||
return subPages.map((page) => formatPagePath((0, import_node_path.join)(rootPath, root), page.path));
|
||||
}).flat()
|
||||
];
|
||||
}
|
||||
function toKebabCase(str) {
|
||||
return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase();
|
||||
}
|
||||
function toPascalCase(str) {
|
||||
return str.replace(/(^\w|-+\w)/g, (match) => match.toUpperCase().replace(/-/g, ""));
|
||||
}
|
||||
function findNode(sfc, rawTagName) {
|
||||
var _a, _b;
|
||||
const templateSource = (_a = sfc.template) == null ? void 0 : _a.content;
|
||||
if (!templateSource)
|
||||
return;
|
||||
let tagName = "";
|
||||
if (templateSource.includes(`<${toKebabCase(rawTagName)}`)) {
|
||||
tagName = toKebabCase(rawTagName);
|
||||
} else if (templateSource.includes(`<${toPascalCase(rawTagName)}`)) {
|
||||
tagName = toPascalCase(rawTagName);
|
||||
}
|
||||
if (!tagName)
|
||||
return;
|
||||
const nodeAst = (_b = sfc.template) == null ? void 0 : _b.ast;
|
||||
if (!nodeAst)
|
||||
return;
|
||||
const traverse = (nodes) => {
|
||||
var _a2;
|
||||
for (const node of nodes) {
|
||||
if (node.type === 1) {
|
||||
if (node.tag === tagName)
|
||||
return node;
|
||||
if ((_a2 = node.children) == null ? void 0 : _a2.length) {
|
||||
const found = traverse(node.children);
|
||||
if (found)
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return void 0;
|
||||
};
|
||||
return traverse(nodeAst.children);
|
||||
}
|
||||
function normalizePlatformPath(id) {
|
||||
const platform = process.env.UNI_PLATFORM;
|
||||
if (!platform)
|
||||
return id;
|
||||
const regex = new RegExp(`\\.${platform}\\.vue$`);
|
||||
if (regex.test(id)) {
|
||||
return id.replace(`.${platform}.`, ".");
|
||||
}
|
||||
return id;
|
||||
}
|
||||
function debounce(fn, delay) {
|
||||
let timer = null;
|
||||
return (...args) => {
|
||||
if (timer)
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), delay);
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
debounce,
|
||||
findNode,
|
||||
formatPagePath,
|
||||
loadPagesJson,
|
||||
normalizePlatformPath,
|
||||
parseSFC,
|
||||
stripJsonComments,
|
||||
toKebabCase,
|
||||
toPascalCase
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { normalizePath } from "vite";
|
||||
async function parseSFC(code) {
|
||||
try {
|
||||
const { parse } = await import("vue/compiler-sfc");
|
||||
return parse(code, { pad: "space" }).descriptor;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function stripJsonComments(str) {
|
||||
return str.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
}
|
||||
function formatPagePath(root, path) {
|
||||
return normalizePath(`${join(root, path)}.vue`).replace(/^[A-Z]:/, (match) => match.toLowerCase());
|
||||
}
|
||||
function loadPagesJson(path, rootPath) {
|
||||
const raw = readFileSync(path, "utf-8");
|
||||
const { pages = [], subPackages = [] } = JSON.parse(stripJsonComments(raw));
|
||||
return [
|
||||
...pages.map((page) => formatPagePath(rootPath, page.path)),
|
||||
...subPackages.map(({ pages: subPages = [], root = "" }) => {
|
||||
return subPages.map((page) => formatPagePath(join(rootPath, root), page.path));
|
||||
}).flat()
|
||||
];
|
||||
}
|
||||
function toKebabCase(str) {
|
||||
return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase();
|
||||
}
|
||||
function toPascalCase(str) {
|
||||
return str.replace(/(^\w|-+\w)/g, (match) => match.toUpperCase().replace(/-/g, ""));
|
||||
}
|
||||
function findNode(sfc, rawTagName) {
|
||||
var _a, _b;
|
||||
const templateSource = (_a = sfc.template) == null ? void 0 : _a.content;
|
||||
if (!templateSource)
|
||||
return;
|
||||
let tagName = "";
|
||||
if (templateSource.includes(`<${toKebabCase(rawTagName)}`)) {
|
||||
tagName = toKebabCase(rawTagName);
|
||||
} else if (templateSource.includes(`<${toPascalCase(rawTagName)}`)) {
|
||||
tagName = toPascalCase(rawTagName);
|
||||
}
|
||||
if (!tagName)
|
||||
return;
|
||||
const nodeAst = (_b = sfc.template) == null ? void 0 : _b.ast;
|
||||
if (!nodeAst)
|
||||
return;
|
||||
const traverse = (nodes) => {
|
||||
var _a2;
|
||||
for (const node of nodes) {
|
||||
if (node.type === 1) {
|
||||
if (node.tag === tagName)
|
||||
return node;
|
||||
if ((_a2 = node.children) == null ? void 0 : _a2.length) {
|
||||
const found = traverse(node.children);
|
||||
if (found)
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return void 0;
|
||||
};
|
||||
return traverse(nodeAst.children);
|
||||
}
|
||||
function normalizePlatformPath(id) {
|
||||
const platform = process.env.UNI_PLATFORM;
|
||||
if (!platform)
|
||||
return id;
|
||||
const regex = new RegExp(`\\.${platform}\\.vue$`);
|
||||
if (regex.test(id)) {
|
||||
return id.replace(`.${platform}.`, ".");
|
||||
}
|
||||
return id;
|
||||
}
|
||||
function debounce(fn, delay) {
|
||||
let timer = null;
|
||||
return (...args) => {
|
||||
if (timer)
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), delay);
|
||||
};
|
||||
}
|
||||
export {
|
||||
debounce,
|
||||
findNode,
|
||||
formatPagePath,
|
||||
loadPagesJson,
|
||||
normalizePlatformPath,
|
||||
parseSFC,
|
||||
stripJsonComments,
|
||||
toKebabCase,
|
||||
toPascalCase
|
||||
};
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { resolve, join } from 'node:path';
|
||||
import process from 'node:process';
|
||||
import { watch, readFileSync } from 'node:fs';
|
||||
import { normalizePath } from 'vite';
|
||||
import { registerRootApp, rebuildRootApp } from './root';
|
||||
import { transformPage } from './page';
|
||||
import { loadPagesJson, normalizePlatformPath, debounce } from './utils';
|
||||
|
||||
interface UniRootOptions {
|
||||
/** 根组件文件名(不含扩展名),默认 App.root */
|
||||
rootFileName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化模块 ID:统一路径分隔符,统一 Windows 盘符为小写
|
||||
*/
|
||||
function normalizeId(id: string) {
|
||||
return normalizePath(id).replace(/^[A-Z]:/, match => match.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* UniApp 虚拟根组件 Vite 插件
|
||||
*
|
||||
* ## 解决的问题
|
||||
* UniApp 不支持原生的根组件包裹机制,导致无法在全局统一注入
|
||||
* u-config-provider、u-toast、u-modal 等组件。
|
||||
*
|
||||
* ## 工作原理
|
||||
* 1. 在 main.ts 中注入 App.root.vue 的导入,并注册为全局组件 global-root-view
|
||||
* 2. 在每个页面的 <template> 中包裹 <global-root-view> 标签
|
||||
* 3. App.root.vue 中的 <slot /> 渲染页面内容
|
||||
*
|
||||
* ## 支持 HMR
|
||||
* pages.json 变更时自动重载页面列表,无需手动重启
|
||||
*
|
||||
* ## 跨端兼容
|
||||
* 纯 Vite 构建时插件,在所有 UniApp 支持的平台(H5、微信小程序、支付宝小程序、
|
||||
* 头条小程序、Android App、iOS App、鸿蒙 App)均可正常工作
|
||||
*/
|
||||
export function UniRoot(options?: UniRootOptions): Plugin {
|
||||
options = {
|
||||
rootFileName: 'App.root',
|
||||
...options
|
||||
};
|
||||
|
||||
const rootPath = process.env.UNI_INPUT_DIR || join(process.cwd(), 'src');
|
||||
const appRootPath = resolve(rootPath, `${options.rootFileName}.vue`);
|
||||
const pagesPath = resolve(rootPath, 'pages.json');
|
||||
|
||||
let pagesJson = loadPagesJson(pagesPath, rootPath);
|
||||
let watcher: ReturnType<typeof watch> | null = null;
|
||||
let hasPlatformPlugin = false;
|
||||
|
||||
const normalizedAppRoot = normalizeId(appRootPath);
|
||||
|
||||
return {
|
||||
name: 'vite-plugin-uni-root',
|
||||
enforce: 'pre', // 在其他插件之前执行,确保页面模板先被包裹
|
||||
|
||||
configResolved({ plugins }) {
|
||||
// 检测是否有 uni-platform 插件,用于处理平台特定页面路径(如 .mp-weixin.vue)
|
||||
hasPlatformPlugin = plugins.some(v => v.name === 'vite-plugin-uni-platform');
|
||||
},
|
||||
|
||||
configureServer(server) {
|
||||
// 监听 pages.json 变更,HMR 热重载页面列表
|
||||
const reload = debounce(() => {
|
||||
try {
|
||||
pagesJson = loadPagesJson(pagesPath, rootPath);
|
||||
server.ws.send({ type: 'full-reload' });
|
||||
} catch (e) {
|
||||
console.error('[vite-plugin-uni-root] pages.json reload failed:', e);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
watcher = watch(pagesPath, eventType => {
|
||||
if (eventType === 'change') reload();
|
||||
});
|
||||
},
|
||||
|
||||
load(id) {
|
||||
const normalizedId = normalizeId(id);
|
||||
// 只拦截根 SFC 请求,不拦截 Vue 子模块请求(如 ?vue&type=script)
|
||||
if (normalizedId === normalizedAppRoot) {
|
||||
const code = readFileSync(appRootPath, 'utf-8');
|
||||
return rebuildRootApp(code).code;
|
||||
}
|
||||
},
|
||||
|
||||
async transform(code, id) {
|
||||
const normalizedId = normalizeId(id);
|
||||
const normalizedRootPath = normalizeId(rootPath);
|
||||
|
||||
// 注入 App.root.vue 的导入,并注册为全局组件 global-root-view
|
||||
if (normalizedId === `${normalizedRootPath}/main.ts` || normalizedId === `${normalizedRootPath}/main.js`) {
|
||||
return registerRootApp(code, options.rootFileName);
|
||||
}
|
||||
|
||||
// App.root.vue 兜底处理(已在 load 中处理,此处只处理根 SFC)
|
||||
if (normalizedId === normalizedAppRoot) {
|
||||
return rebuildRootApp(code);
|
||||
}
|
||||
|
||||
// 页面模板包裹 <global-root-view>
|
||||
const pageId = hasPlatformPlugin ? normalizePlatformPath(normalizedId) : normalizedId;
|
||||
const isPage = pagesJson.some(p => pageId === p || pageId.startsWith(`${p}?`));
|
||||
if (isPage) {
|
||||
return transformPage(code);
|
||||
}
|
||||
},
|
||||
|
||||
buildEnd() {
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
watcher = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default UniRoot;
|
||||
export type { UniRootOptions };
|
||||
@@ -0,0 +1,77 @@
|
||||
import { parseSFC, findNode } from './utils';
|
||||
|
||||
/**
|
||||
* 页面模板转换:将页面内容包裹在 <global-root-view> 中
|
||||
*
|
||||
* <global-root-view> 是 App.root.vue 注册的全局组件,
|
||||
* 其模板中包含 <slot />,页面内容通过插槽传入。
|
||||
*
|
||||
* 处理逻辑:
|
||||
* 1. 解析 SFC,定位 <template> 标签的起止位置
|
||||
* 2. 提取模板内容,查找 PageMeta 节点(如有则提取到包裹层外部)
|
||||
* 3. 将剩余内容包裹在 <global-root-view>...</global-root-view> 中
|
||||
*
|
||||
* 降级机制:当 vue/compiler-sfc 不可用(如 HBuilderX 项目)时,
|
||||
* 使用正则匹配 <page-meta> 标签替代 AST 解析。
|
||||
*/
|
||||
export async function transformPage(code: string) {
|
||||
const sfc = await parseSFC(code);
|
||||
|
||||
// 用正则定位 <template> 开头标签
|
||||
const openMatch = code.match(/<template\b[^>]*>/);
|
||||
if (!openMatch) return null;
|
||||
|
||||
// 使用 lastIndexOf 定位最后一个 </template>,即根 <template> 的闭合标签
|
||||
// 避免匹配到模板内具名插槽 <template #slot> 的闭合标签
|
||||
const closeTagStart = code.lastIndexOf('</template>');
|
||||
if (closeTagStart === -1) return null;
|
||||
|
||||
const openTagEnd = openMatch.index! + openMatch[0].length;
|
||||
const content = code.slice(openTagEnd, closeTagStart);
|
||||
|
||||
let pageMetaSource = '';
|
||||
let newContent = content;
|
||||
|
||||
if (sfc?.template) {
|
||||
// AST 模式:通过 vue/compiler-sfc 解析,精确定位 PageMeta 节点
|
||||
const pageMetaNode = findNode(sfc, 'PageMeta');
|
||||
if (pageMetaNode) {
|
||||
pageMetaSource = pageMetaNode.loc.source;
|
||||
const metaStart = pageMetaNode.loc.start.offset;
|
||||
const metaEnd = pageMetaNode.loc.end.offset;
|
||||
|
||||
// pageMetaNode.loc 的 offset 是相对于整个文件的,转换为相对于 content 的位置
|
||||
const metaStartInContent = metaStart - openTagEnd;
|
||||
const metaEndInContent = metaEnd - openTagEnd;
|
||||
|
||||
newContent = content.slice(0, metaStartInContent) + content.slice(metaEndInContent);
|
||||
}
|
||||
} else {
|
||||
// 降级模式:vue/compiler-sfc 不可用,用正则匹配 <page-meta> 标签
|
||||
const pageMetaMatch = content.match(/<page-meta\b[^>]*>[\s\S]*?<\/page-meta>/);
|
||||
if (pageMetaMatch) {
|
||||
pageMetaSource = pageMetaMatch[0];
|
||||
newContent = content.replace(pageMetaMatch[0], '');
|
||||
} else {
|
||||
// 也匹配自闭合的 <page-meta ... />
|
||||
const selfClosingMatch = content.match(/<page-meta\b[^>]*\/>/);
|
||||
if (selfClosingMatch) {
|
||||
pageMetaSource = selfClosingMatch[0];
|
||||
newContent = content.replace(selfClosingMatch[0], '');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// page-meta 放在包裹层外部,内容包裹在 <global-root-view> 中
|
||||
const wrappedContent = `\n${pageMetaSource}\n<global-root-view>${newContent}</global-root-view>\n`;
|
||||
|
||||
return {
|
||||
code: code.slice(0, openTagEnd) + wrappedContent + code.slice(closeTagStart),
|
||||
map: {
|
||||
version: 3 as const,
|
||||
sources: [] as string[],
|
||||
names: [] as string[],
|
||||
mappings: ''
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* 创建一个最小的 sourcemap,用于满足 Vite/Rollup 的 sourcemap 要求。
|
||||
*
|
||||
* 这是一个空映射的 sourcemap(mappings 为空字符串),不提供精确的源码映射,
|
||||
* 但可以避免 "Sourcemap is likely to be incorrect" 警告。
|
||||
* 调试器会回退到显示转换后的代码,不影响功能。
|
||||
*
|
||||
* 纯 JS 实现,无需第三方依赖。
|
||||
*/
|
||||
function createEmptySourcemap() {
|
||||
return {
|
||||
version: 3 as const,
|
||||
sources: [] as string[],
|
||||
names: [] as string[],
|
||||
mappings: ''
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 向 main.ts 注入 App.root.vue 的导入和全局注册
|
||||
*
|
||||
* 流程:
|
||||
* 1. 在文件顶部插入 `import GlobalRootView from "./App.root.vue"`
|
||||
* 2. 在 createSSRApp 之后插入 `app.component("global-root-view", GlobalRootView)`
|
||||
*
|
||||
* 注:GlobalRootView 仅为 main.ts 中的局部变量名,
|
||||
* 实际组件就是 App.root.vue,页面通过 <global-root-view> 标签使用。
|
||||
*/
|
||||
export function registerRootApp(code: string, fileName: string = 'App.root') {
|
||||
const importCode = `import GlobalRootView from "./${fileName}.vue";`;
|
||||
const vueUseComponentCode = `app.component("global-root-view", GlobalRootView);`;
|
||||
|
||||
let newCode = importCode + '\n' + code;
|
||||
|
||||
// 在 createSSRApp 赋值语句之后插入组件注册代码
|
||||
const ssrAppMatch = newCode.match(/(const\s+app\s*=\s*createSSRApp\([^)]+\);)/);
|
||||
if (ssrAppMatch) {
|
||||
newCode = newCode.replace(/(const\s+app\s*=\s*createSSRApp\([^)]+\);)/, `$1\n ${vueUseComponentCode}`);
|
||||
} else {
|
||||
// 兜底:在 return { 之前插入
|
||||
newCode = newCode.replace(/(createApp[\s\S]*?)(return\s*\{)/, `$1${vueUseComponentCode}\n $2`);
|
||||
}
|
||||
|
||||
return { code: newCode, map: createEmptySourcemap() };
|
||||
}
|
||||
|
||||
/**
|
||||
* App.root.vue 模板中已使用 <slot /> 作为子内容插槽,
|
||||
* 无需替换,直接透传。
|
||||
*/
|
||||
export function rebuildRootApp(code: string) {
|
||||
return { code, map: createEmptySourcemap() };
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { normalizePath } from 'vite';
|
||||
|
||||
/**
|
||||
* Parse Vue SFC file, return descriptor
|
||||
*
|
||||
* When vue/compiler-sfc is not available (e.g. HBuilderX projects where
|
||||
* vue is not in node_modules), returns null instead of throwing.
|
||||
* Callers should fall back to regex-based matching.
|
||||
*/
|
||||
export async function parseSFC(code: string) {
|
||||
try {
|
||||
const { parse } = await import('vue/compiler-sfc');
|
||||
return parse(code, { pad: 'space' }).descriptor;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip JSON comments (single-line and multi-line)
|
||||
*/
|
||||
export function stripJsonComments(str: string): string {
|
||||
return str.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert pages.json path to absolute file path
|
||||
*/
|
||||
export function formatPagePath(root: string, path: string) {
|
||||
return normalizePath(`${join(root, path)}.vue`).replace(/^[A-Z]:/, match => match.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Load pages.json and resolve all page paths (main + subPackages)
|
||||
*/
|
||||
export function loadPagesJson(path: string, rootPath: string): string[] {
|
||||
const raw = readFileSync(path, 'utf-8');
|
||||
const { pages = [], subPackages = [] } = JSON.parse(stripJsonComments(raw));
|
||||
|
||||
return [
|
||||
...pages.map((page: any) => formatPagePath(rootPath, page.path)),
|
||||
...subPackages
|
||||
.map(({ pages: subPages = [], root = '' }: any) => {
|
||||
return subPages.map((page: any) => formatPagePath(join(rootPath, root), page.path));
|
||||
})
|
||||
.flat()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* camelCase to kebab-case: PageMeta -> page-meta
|
||||
*/
|
||||
export function toKebabCase(str: string) {
|
||||
return str
|
||||
.replace(/([a-z])([A-Z])/g, '$1-$2')
|
||||
.replace(/[_\s]+/g, '-')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* kebab-case to PascalCase: page-meta -> PageMeta
|
||||
*/
|
||||
export function toPascalCase(str: string) {
|
||||
return str.replace(/(^\w|-+\w)/g, match => match.toUpperCase().replace(/-/g, ''));
|
||||
}
|
||||
|
||||
interface TagNode {
|
||||
loc: {
|
||||
source: string;
|
||||
start: { offset: number };
|
||||
end: { offset: number };
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a tag node in SFC template AST by tag name
|
||||
* Supports both kebab-case and PascalCase
|
||||
*/
|
||||
export function findNode(sfc: any, rawTagName: string): TagNode | undefined {
|
||||
const templateSource = sfc.template?.content;
|
||||
if (!templateSource) return;
|
||||
|
||||
let tagName = '';
|
||||
if (templateSource.includes(`<${toKebabCase(rawTagName)}`)) {
|
||||
tagName = toKebabCase(rawTagName);
|
||||
} else if (templateSource.includes(`<${toPascalCase(rawTagName)}`)) {
|
||||
tagName = toPascalCase(rawTagName);
|
||||
}
|
||||
|
||||
if (!tagName) return;
|
||||
|
||||
const nodeAst = sfc.template?.ast;
|
||||
if (!nodeAst) return;
|
||||
|
||||
// Recursively traverse AST to find the target node
|
||||
const traverse = (nodes: any): TagNode | undefined => {
|
||||
for (const node of nodes) {
|
||||
if (node.type === 1) {
|
||||
if (node.tag === tagName) return node;
|
||||
if (node.children?.length) {
|
||||
const found = traverse(node.children);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
return traverse(nodeAst.children);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize platform-specific page paths (.mp-weixin.vue -> .vue)
|
||||
*/
|
||||
export function normalizePlatformPath(id: string) {
|
||||
const platform = process.env.UNI_PLATFORM;
|
||||
if (!platform) return id;
|
||||
|
||||
const regex = new RegExp(`\\.${platform}\\.vue$`);
|
||||
if (regex.test(id)) {
|
||||
return id.replace(`.${platform}.`, '.');
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Debounce utility
|
||||
*/
|
||||
export function debounce<T extends (...args: any[]) => void>(fn: T, delay: number) {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
return (...args: Parameters<T>) => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), delay);
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user