@uni-helper/vite-plugin-uni-pages 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +21 -9
- package/dist/index.d.mts +9 -0
- package/dist/index.mjs +217 -20
- package/package.json +2 -2
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2022 KeJun
|
|
3
|
+
Copyright (c) 2022-present KeJun & uni-helper & Collaborators
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
package/README.md
CHANGED
|
@@ -98,9 +98,9 @@ await pages.prepare({ platformSuffix: false })
|
|
|
98
98
|
| `root?: string` | 提前指定 Vite 项目根目录,默认使用 `VITE_ROOT_DIR` 或当前工作目录;相对路径以当前工作目录为基准 |
|
|
99
99
|
| `platformSuffix: boolean` | 必填,声明是否使用 UniPlatform 文件名后缀规则;启用 `@uni-helper/vite-plugin-uni-platform` 时传 `true`,其余场景传 `false` |
|
|
100
100
|
|
|
101
|
-
通过 uni-app 的开发或构建命令调用该配置。编译平台读取调用时的 `process.env.UNI_PLATFORM`;独立脚本需要提前设置它。准备阶段 Vite
|
|
101
|
+
通过 uni-app 的开发或构建命令调用该配置。编译平台读取调用时的 `process.env.UNI_PLATFORM`;独立脚本需要提前设置它。准备阶段 Vite 尚未提供解析后的环境和 `define`,配置若依赖 `.env` 变量,应先用 Vite `loadEnv(mode, root)` 加载,再将必需变量写入 `process.env`,保留已有进程变量的优先级;仅调用 `loadEnv()` 不会设置进程环境。自定义 Vite `root` 时,向 `prepare()` 传入相同的根目录。
|
|
102
102
|
|
|
103
|
-
-
|
|
103
|
+
- 同一次准备期间,相同根目录、编译平台和后缀规则的并发或重复调用只初始化一次,并始终使用本轮的兜底环境。Vite 接管会等待准备成功,复用上下文并切换到正式环境重新生成;准备失败时保留原错误。Vite 会话结束后再次调用会重新读取配置和页面。
|
|
104
104
|
- Vite 接管时会核对根目录、编译平台和 UniPlatform 状态,不一致会报错;接管后再次调用也必须保持一致。成功调用过 `prepare()` 后,这个核对一直有效。
|
|
105
105
|
- 配置加载、文件写入或锁获取失败会拒绝 Promise,修复后可再次调用 `prepare()`。
|
|
106
106
|
- 准备前应完成源码与配置的创建;准备完成到文件监听建立之间的修改不保证被自动发现。
|
|
@@ -135,7 +135,7 @@ Vite 在创建 Rollup 构建图或开发服务器之前就退出时(例如其
|
|
|
135
135
|
|
|
136
136
|
占位文件只在能推导出的输出目录已经存在时创建。目录不存在时不在那个位置新建目录:`root` 优先取 `VITE_ROOT_DIR`,没设时取当前工作目录,而这个工作目录很可能不是真正的项目根,在它下面创建 `src` 会把目录建错地方。这时直接跑完整生成;如果 Vite 传入的 `root` 又是错的,生成会以 `ENOENT` 失败并指明路径。
|
|
137
137
|
|
|
138
|
-
`prepare()`
|
|
138
|
+
`prepare()` 和 Vite 接管时的再次生成都不会刷新下游插件已经缓存的配置。需要读取完整配置的插件应在准备完成后创建,它们依赖的环境值必须在准备之前提供。
|
|
139
139
|
|
|
140
140
|
### 配置依赖热更新
|
|
141
141
|
|
|
@@ -211,6 +211,16 @@ export const title = '首页'
|
|
|
211
211
|
|
|
212
212
|
对配置入口及打包进配置的脚本模块,`__dirname`、`__filename`、`import.meta.url`、`import.meta.dirname`、`import.meta.filename` 同样对应各自源文件。`require.resolve()` 和 `import.meta.resolve()` 从调用模块的位置解析目标,只返回路径或 URL,不加载目标模块。运行时由 Node 加载的目标不经过这层转换,遵循目标模块自身的 ESM 或 CommonJS 语义。
|
|
213
213
|
|
|
214
|
+
每个模块都有独立的完整 `import.meta` 对象,解构、别名和计算式访问都保留各自的源位置,例如 `const { url, resolve } = import.meta`、`const meta = import.meta` 和 `import.meta[key]`。`import.meta.main` 为 `false`。
|
|
215
|
+
|
|
216
|
+
`import.meta.env` 以 Vite 解析后的 `config.env` 为基础:按 `envPrefix` 筛选的环境变量(默认前缀为 `VITE_`)、`BASE_URL`、`MODE`、`DEV`、`PROD`,初始补入 `SSR: false`,再应用 `define` 中 `import.meta.env.*` 条目的覆盖。同一轮加载的所有模块共享这个 env 对象,直接访问、解构和别名的结果一致。`process.env` 里同名的前缀变量优先于 `.env` 文件,前缀筛选和优先级由 Vite 处理。
|
|
217
|
+
|
|
218
|
+
环境定义的字符串按 esbuild 替换表达式处理,其他值按 JSON 编码。例如,字符串值写作 `define: { 'import.meta.env.VITE_TITLE': JSON.stringify('首页') }`;`'globalThis.APP_VERSION'` 表示读取全局属性。表达式在字段首次读取时由 Node 求值,成功结果在本轮加载中共享并缓存。未读取的浏览器专用定义不会因缺少浏览器全局而影响配置加载;读取时仍要求相关全局在 Node 中可用,插件不会提供 `window` 等浏览器对象。其他 `define` 条目不应用于配置图。
|
|
219
|
+
|
|
220
|
+
`prepare()` 拿不到 Vite 的环境和 `define`,仅使用进程环境中的 `VITE_` 变量兜底,并提供 `BASE_URL: '/'`、由 `NODE_ENV` 推导的 `MODE` / `DEV` / `PROD` 和 `SSR: false`。准备成功后,Vite 接管并使用正式环境重新生成;接管前的消费者仍需要提前提供必需变量。自定义前缀不参与准备阶段的 `import.meta.env` 兜底,需要提前使用时可在配置中显式读取对应的 `process.env` 值。
|
|
221
|
+
|
|
222
|
+
`import.meta` 的其余成员不由插件提供,读到的是 `undefined`。`typeof import.meta.glob === 'function'` 这类判断会走 false 分支,`import.meta.hot` 也是 `undefined`。插件对静态可识别的直接成员访问输出带文件位置的警告。
|
|
223
|
+
|
|
214
224
|
运行时解析区分包的 `import` / `require` 条件导出,支持模块所属包的 `#imports`。Node 自定义 loader、`--conditions` 等额外命令行解析选项不在此解析约定内。`fs.readFile()` 等自行读取、`node_modules` 变更和应用的 `resolve.alias` 不在自动依赖监听范围内。
|
|
215
225
|
|
|
216
226
|
#### transform 与自定义 parser
|
|
@@ -949,7 +959,7 @@ pipeline.ts 纯流水线入口:createPages / generateAll,root 和 plat
|
|
|
949
959
|
config-loader.ts 配置加载:unconfig 发现与回调、内存转换、隔离产物、本地依赖与恢复输入
|
|
950
960
|
config-watch.ts 配置监听计划:来源、依赖与恢复候选归一化为文件、恢复目录与注册路径,
|
|
951
961
|
并负责配置事件判定
|
|
952
|
-
config-source.ts
|
|
962
|
+
config-source.ts 源位置适配:每模块 import.meta 与运行时解析、共享环境及定义覆盖、源码映射
|
|
953
963
|
directories.ts 目录发现:glob 展开、subPackages 来源发现与扫描目录投影
|
|
954
964
|
scan-plan.ts 扫描计划:一次发现主包目录、分包来源、最终 root 与规则,作为不可变视图
|
|
955
965
|
page-rules.ts 页面规则:基于 Vite root 编译排除模式,统一扫描与事件判定
|
|
@@ -985,7 +995,7 @@ types.ts 公共类型定义(Options / UserOptions / ResolvedOptions
|
|
|
985
995
|
index.ts
|
|
986
996
|
├─ context.ts(编排核心)
|
|
987
997
|
│ ├─ config-loader.ts 配置装载、产物身份与恢复输入
|
|
988
|
-
│ │ ├─ config-source.ts
|
|
998
|
+
│ │ ├─ config-source.ts 源位置适配、共享环境与运行时解析
|
|
989
999
|
│ │ └─ config-watch.ts 监听计划与配置事件判定(反向读取加载器路径工具)
|
|
990
1000
|
│ ├─ options.ts ── scan-plan.ts 选项解析、目录发现与不可变扫描计划
|
|
991
1001
|
│ │ ├─ directories.ts 目录来源、root 决议与扫描投影
|
|
@@ -1025,9 +1035,9 @@ pipeline.ts ── context.ts 测试与外部调用的流水线入
|
|
|
1025
1035
|
|
|
1026
1036
|
`loadScript()` 接收原入口路径和经过可选 transform 处理的入口文本。它通过 `bundle-require` 调用 esbuild 打包并执行脚本,过程如下:
|
|
1027
1037
|
|
|
1028
|
-
1. 在 `node_modules/.cache/uni-pages/` 下创建这一轮加载独占的 `load-*` 目录,并写入公共辅助模块 `runtime.mjs
|
|
1038
|
+
1. 在 `node_modules/.cache/uni-pages/` 下创建这一轮加载独占的 `load-*` 目录,并写入公共辅助模块 `runtime.mjs`。它携带本轮环境值,以及经 esbuild 校验和替换的 `import.meta.env.*` 定义表达式。
|
|
1029
1039
|
2. esbuild 解析入口和静态依赖。`onResolve` 按导入位置解析目标,并记录缺失导入的恢复候选;`onLoad` 读取模块,将需要转换的脚本文本与原文件路径交给 `transformConfigSource()`。
|
|
1030
|
-
3. `transformConfigSource()` 在内存中为每个模块注入绑定原文件位置的 `require
|
|
1040
|
+
3. `transformConfigSource()` 在内存中为每个模块注入绑定原文件位置的 `require`、完整 `import.meta` 对象和动态导入函数,保留可由 esbuild 打包的调用,并生成源码映射。各模块的 `import.meta.env` 指向 `runtime.mjs` 导出的同一份对象,静态可识别的不可用成员访问在这一步被收集并交给 logger。
|
|
1031
1041
|
4. esbuild 将转换后的配置模块和所需辅助代码打包为 `config.mjs`,`bundle-require` 加载执行它;加载器提取配置对象,并记录参与打包的本地依赖。
|
|
1032
1042
|
5. 成功或失败都由加载器统一尝试删除本轮 `load-*` 目录,包括打包执行文件;删除失败只记录调试日志,不影响配置结果或原始错误。加载失败时保留已尝试的源路径及适用的缺失导入候选,供后续文件事件触发重试。
|
|
1033
1043
|
|
|
@@ -1042,7 +1052,7 @@ node_modules/.cache/uni-pages/
|
|
|
1042
1052
|
|
|
1043
1053
|
| 文件 | 内容来源 | 用途 |
|
|
1044
1054
|
| --- | --- | --- |
|
|
1045
|
-
| `runtime.mjs` | `configRuntimeSource()`
|
|
1055
|
+
| `runtime.mjs` | `await configRuntimeSource()` 得到的 JavaScript 源码 | 提供共用的 `env` 和 `createRequire`、`createMeta`、`resolveFrom`、`importFrom` 等助手;`createMeta` 按源模块路径创建独立对象,环境定义按字段首次读取时在 Node 中求值并缓存本轮结果 |
|
|
1046
1056
|
| `config.mjs` | esbuild 汇总入口文本、打包的依赖及辅助代码生成 | 由 Node 执行并导出配置对象;外部依赖保留为导入,运行时动态目标由助手解析后加载 |
|
|
1047
1057
|
|
|
1048
1058
|
例如,`config/global-style.ts` 中的 `import(target)` 会被转换成效果相当于 `importFrom(target, 'file:///app/config/global-style.ts')` 的调用。`importFrom` 使用 `import-meta-resolve` 将目标解析成 URL,再调用 Node 的 `import()`。`require(target)` 则使用 Node 的 `createRequire(原文件路径)`。每个模块分别携带自己的源位置,执行文件所在的临时目录不会改变这些调用的解析基准。
|
|
@@ -1063,7 +1073,7 @@ node_modules/.cache/uni-pages/
|
|
|
1063
1073
|
插件通过 Vite 的生命周期钩子驱动,顺序如下:
|
|
1064
1074
|
|
|
1065
1075
|
1. **插件工厂调用**(同步):预检 `pages.json` 是否存在且合法(此时 `config.root` 未知,回退到 `VITE_ROOT_DIR` / `process.cwd()` 解析路径)
|
|
1066
|
-
2. **`configResolved`**(异步):占用当前实例,创建 `PageContext`
|
|
1076
|
+
2. **`configResolved`**(异步):占用当前实例,创建 `PageContext` 或等待匹配的 `prepare()` 成功后接管,检测是否与 `vite-plugin-uni-platform` 协同,使用 Vite 环境与环境定义完成 pages.json 生成;已有准备结果时按正式环境重新生成。`build --watch` 模式下另建 watcher,接收配置文件事件与页面目录结构通知,同时启动自有页面监听器
|
|
1067
1077
|
3. **`configureServer`**(dev):从 Vite 的 `server.watcher` 接收配置监听计划命中与页面目录结构通知,并按 Vite 的监听开关、忽略规则和轮询设置启动自有页面监听器;产物更新后失效虚拟模块并通知浏览器 full-reload
|
|
1068
1078
|
4. **`options`**(build):将本插件的虚拟模块与关闭钩子绑定到当前会话,供 Rollup 构建使用;watcher 各轮沿用该绑定,已关闭构建的迟到钩子及已排队轮次仍属于原会话
|
|
1069
1079
|
5. **`transform`**:从 vue / nvue / uvue 文件中移除 `definePage` 宏调用,避免运行时报错
|
|
@@ -1086,10 +1096,12 @@ node_modules/.cache/uni-pages/
|
|
|
1086
1096
|
## 感谢
|
|
1087
1097
|
|
|
1088
1098
|
- [hannoeru/vite-plugin-pages](https://github.com/hannoeru/vite-plugin-pages)
|
|
1099
|
+
- [skiyee/oiyo](https://oiyo.js.org)
|
|
1089
1100
|
- [uni-ku/pages-json](https://github.com/uni-ku/pages-json)
|
|
1090
1101
|
|
|
1091
1102
|
## 关联项目
|
|
1092
1103
|
|
|
1104
|
+
- [skiyee/oiyo](https://oiyo.js.org) - uni-app 增强型工程框架
|
|
1093
1105
|
- [@uni-helper/vite-plugin-uni-pages](https://github.com/uni-helper/vite-plugin-uni-pages/tree/main/packages/core) - 使用 TypeScript 编写 uni-app 的 pages.json,支持约定式路由
|
|
1094
1106
|
- [@uni-helper/pages-json-schema](https://github.com/uni-helper/vite-plugin-uni-pages/tree/main/packages/schema) - 为 uni-app 的 pages.json 提供 schema
|
|
1095
1107
|
- [@uni-helper/uni-pages-types](https://github.com/uni-helper/vite-plugin-uni-pages/tree/main/packages/types) - 为 uni-app 的 pages.json 提供 TypeScript 类型
|
package/dist/index.d.mts
CHANGED
|
@@ -644,6 +644,15 @@ export declare class PageContext {
|
|
|
644
644
|
* @param logger - Vite logger 实例
|
|
645
645
|
*/
|
|
646
646
|
setLogger(logger: Logger): void;
|
|
647
|
+
/**
|
|
648
|
+
* 设置配置图里 import.meta.env 的值
|
|
649
|
+
*
|
|
650
|
+
* @description 下一次配置加载时生效,不会自行触发页面生成
|
|
651
|
+
* @param env - Vite 解析后的环境值
|
|
652
|
+
* @param define - Vite 的定义映射,只应用 import.meta.env.* 条目
|
|
653
|
+
* @returns 首次用上 Vite 的 env 时为 `true`,已经生成的 pages.json 需要重算
|
|
654
|
+
*/
|
|
655
|
+
setConfigEnv(env: Record<string, unknown>, define?: Record<string, unknown>): boolean;
|
|
647
656
|
/**
|
|
648
657
|
* 加载用户页面配置文件(如 pages.config.ts)
|
|
649
658
|
* 使用 unconfig 加载配置,支持多种配置文件格式
|
package/dist/index.mjs
CHANGED
|
@@ -19,14 +19,56 @@ import Debug from "debug";
|
|
|
19
19
|
import { platform } from "@uni-helper/uni-env";
|
|
20
20
|
import { CommentArray, parse, stringify } from "comment-json";
|
|
21
21
|
import groupBy from "lodash.groupby";
|
|
22
|
+
import writeFileAtomic from "write-file-atomic";
|
|
22
23
|
import lockfile from "proper-lockfile";
|
|
23
24
|
import { escapePath, globSync, isDynamicPattern } from "tinyglobby";
|
|
24
25
|
import picomatch from "picomatch";
|
|
25
26
|
import vm from "node:vm";
|
|
26
27
|
import { parse as parse$1 } from "@vue/compiler-sfc";
|
|
27
28
|
import * as ts from "typescript";
|
|
28
|
-
import writeFileAtomic from "write-file-atomic";
|
|
29
29
|
//#region src/config-source.ts
|
|
30
|
+
/** 加载器给 import.meta 提供取值的成员,其余成员保持 undefined */
|
|
31
|
+
const providedMetaMembers = /* @__PURE__ */ new Set([
|
|
32
|
+
"dirname",
|
|
33
|
+
"env",
|
|
34
|
+
"filename",
|
|
35
|
+
"main",
|
|
36
|
+
"resolve",
|
|
37
|
+
"url"
|
|
38
|
+
]);
|
|
39
|
+
/**
|
|
40
|
+
* 找出模块里访问了加载器不提供的 import.meta 成员的位置
|
|
41
|
+
*
|
|
42
|
+
* @description 只在源码出现 `import.meta` 时解析;语法错误留给 esbuild 报,这里不重复
|
|
43
|
+
* @param code 模块的原始源码,必须早于 esbuild 的 define 替换
|
|
44
|
+
* @param filename 模块的绝对路径,决定按 TS 还是 JS 语法解析
|
|
45
|
+
* @returns 按源码顺序排列的每处访问
|
|
46
|
+
*/
|
|
47
|
+
function findUnprovidedMetaMembers(code, filename) {
|
|
48
|
+
if (!code.includes("import.meta")) return [];
|
|
49
|
+
const extension = path.extname(filename).slice(1);
|
|
50
|
+
const lang = extension === "tsx" ? "tsx" : extension === "jsx" ? "jsx" : /^(?:ts|mts|cts)$/.test(extension) ? "ts" : "js";
|
|
51
|
+
let ast;
|
|
52
|
+
try {
|
|
53
|
+
ast = babelParse(code, lang, { allowReturnOutsideFunction: true });
|
|
54
|
+
} catch {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
const warnings = [];
|
|
58
|
+
walkAST(ast, { enter(node) {
|
|
59
|
+
if (node.type !== "MemberExpression" || node.object.type !== "MetaProperty") return;
|
|
60
|
+
if (node.object.meta.name !== "import" || node.object.property.name !== "meta") return;
|
|
61
|
+
const member = node.property.type === "Identifier" ? node.property.name : node.property.type === "StringLiteral" ? node.property.value : void 0;
|
|
62
|
+
if (member === void 0 || providedMetaMembers.has(member)) return;
|
|
63
|
+
warnings.push({
|
|
64
|
+
file: filename,
|
|
65
|
+
line: node.loc?.start.line ?? 0,
|
|
66
|
+
column: (node.loc?.start.column ?? 0) + 1,
|
|
67
|
+
member
|
|
68
|
+
});
|
|
69
|
+
} });
|
|
70
|
+
return warnings;
|
|
71
|
+
}
|
|
30
72
|
/** 判断导入表达式能否交给 esbuild 收集依赖,未匹配的目标由运行时助手解析 */
|
|
31
73
|
function isBundledSpecifier(node) {
|
|
32
74
|
if (!node) return false;
|
|
@@ -43,10 +85,11 @@ function isBundledSpecifier(node) {
|
|
|
43
85
|
* 将脚本转换为绑定原文件位置的 JavaScript
|
|
44
86
|
*
|
|
45
87
|
* @description 注入运行时解析助手;可打包的调用及用户声明的局部 require 保持原语义
|
|
88
|
+
* import.meta 的解构、别名和计算式访问使用当前模块的源位置,各模块共享同一份 env
|
|
46
89
|
* @param code 当前模块的源码文本
|
|
47
90
|
* @param filename 当前模块的原始绝对路径,作为该模块运行时解析的基准
|
|
48
91
|
* @param runtime 本轮生成的公共辅助模块路径,供转换后的代码导入
|
|
49
|
-
* @returns 转换后的 JavaScript
|
|
92
|
+
* @returns 转换后的 JavaScript 及其发现的 import.meta 成员问题
|
|
50
93
|
*/
|
|
51
94
|
async function transformConfigSource(code, filename, runtime) {
|
|
52
95
|
let prefix = "__uni_pages_source";
|
|
@@ -56,6 +99,8 @@ async function transformConfigSource(code, filename, runtime) {
|
|
|
56
99
|
const importName = `${prefix}_import`;
|
|
57
100
|
const extension = path.extname(filename).slice(1);
|
|
58
101
|
const loader = extension === "jsx" || extension === "tsx" ? extension : /^(?:c|m)?js$/.test(extension) ? "js" : "ts";
|
|
102
|
+
const directory = path.dirname(filename);
|
|
103
|
+
const url = pathToFileURL(filename).href;
|
|
59
104
|
const result = await transform(code, {
|
|
60
105
|
loader,
|
|
61
106
|
sourcefile: filename,
|
|
@@ -64,7 +109,7 @@ async function transformConfigSource(code, filename, runtime) {
|
|
|
64
109
|
define: {
|
|
65
110
|
"require": requireName,
|
|
66
111
|
"import.meta": metaName,
|
|
67
|
-
"__dirname": JSON.stringify(
|
|
112
|
+
"__dirname": JSON.stringify(directory),
|
|
68
113
|
"__filename": JSON.stringify(filename)
|
|
69
114
|
}
|
|
70
115
|
});
|
|
@@ -73,12 +118,11 @@ async function transformConfigSource(code, filename, runtime) {
|
|
|
73
118
|
if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === requireName && isBundledSpecifier(node.arguments[0])) node.callee.name = "require";
|
|
74
119
|
if (node.type === "ImportExpression" && !isBundledSpecifier(node.source)) this.replace(callExpression(identifier(importName), [node.source, ...node.options ? [node.options] : []]));
|
|
75
120
|
} });
|
|
76
|
-
const url = JSON.stringify(pathToFileURL(filename).href);
|
|
77
121
|
const helpers = babelParse(`
|
|
78
122
|
import { createRequire as ${prefix}_createRequire, createMeta as ${prefix}_createMeta, importFrom as ${prefix}_importFrom } from ${JSON.stringify(runtime)};
|
|
79
123
|
const ${requireName} = ${prefix}_createRequire(${JSON.stringify(filename)});
|
|
80
|
-
const ${metaName} = ${prefix}_createMeta(${JSON.stringify(filename)}, ${url}, ${JSON.stringify(
|
|
81
|
-
const ${importName} = (specifier, options) => ${prefix}_importFrom(specifier, ${url}, options);
|
|
124
|
+
const ${metaName} = ${prefix}_createMeta(${JSON.stringify(filename)}, ${JSON.stringify(url)}, ${JSON.stringify(directory)});
|
|
125
|
+
const ${importName} = (specifier, options) => ${prefix}_importFrom(specifier, ${JSON.stringify(url)}, options);
|
|
82
126
|
`, "js");
|
|
83
127
|
removePropertiesDeep(helpers);
|
|
84
128
|
ast.body.unshift(...helpers.body);
|
|
@@ -87,20 +131,65 @@ const ${importName} = (specifier, options) => ${prefix}_importFrom(specifier, ${
|
|
|
87
131
|
sourceFileName: filename,
|
|
88
132
|
inputSourceMap: JSON.parse(result.map)
|
|
89
133
|
}, result.code);
|
|
90
|
-
return
|
|
134
|
+
return {
|
|
135
|
+
code: `${output.code}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(output.map)).toString("base64")}`,
|
|
136
|
+
warnings: findUnprovidedMetaMembers(code, filename)
|
|
137
|
+
};
|
|
91
138
|
}
|
|
92
139
|
/**
|
|
93
140
|
* 生成配置执行所需的公共辅助模块源码
|
|
94
141
|
*
|
|
95
|
-
* @description 调用方将返回文本写入本轮 runtime.mjs
|
|
96
|
-
* @
|
|
142
|
+
* @description 调用方将返回文本写入本轮 runtime.mjs;env 是配置图里 import.meta.env 的唯一一份
|
|
143
|
+
* @param env import.meta.env 的值,来自 Vite 解析后的 config.env 或进程环境兜底
|
|
144
|
+
* @param define Vite 的定义映射,只应用 import.meta.env.* 条目
|
|
145
|
+
* @returns 供配置打包使用的 ESM 源码
|
|
97
146
|
*/
|
|
98
|
-
function configRuntimeSource() {
|
|
147
|
+
async function configRuntimeSource(env, define = {}) {
|
|
148
|
+
const prefix = "import.meta.env.";
|
|
149
|
+
const overrides = Object.entries(define).filter(([key]) => key.startsWith(prefix));
|
|
150
|
+
let envSource = `export const env = ${JSON.stringify(env)};`;
|
|
151
|
+
if (overrides.length) {
|
|
152
|
+
const values = overrides.map(([key]) => `${JSON.stringify(key.slice(16))}: () => ${key}`);
|
|
153
|
+
const transformed = await transform(`const overrides = { ${values.join(", ")} };`, {
|
|
154
|
+
loader: "js",
|
|
155
|
+
target: "node22",
|
|
156
|
+
define: Object.fromEntries(overrides.map(([key, value]) => [key, typeof value === "string" ? value : JSON.stringify(value) ?? "undefined"]))
|
|
157
|
+
});
|
|
158
|
+
envSource += `
|
|
159
|
+
${transformed.code}
|
|
160
|
+
function setEnvValue(key, value) {
|
|
161
|
+
Object.defineProperty(env, key, { value, enumerable: true, configurable: true, writable: true });
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
for (const [key, read] of Object.entries(overrides)) {
|
|
165
|
+
let loaded = false;
|
|
166
|
+
let value;
|
|
167
|
+
Object.defineProperty(env, key, {
|
|
168
|
+
enumerable: true,
|
|
169
|
+
configurable: true,
|
|
170
|
+
get() {
|
|
171
|
+
if (!loaded) {
|
|
172
|
+
value = read();
|
|
173
|
+
loaded = true;
|
|
174
|
+
}
|
|
175
|
+
if (Object.getOwnPropertyDescriptor(env, key)?.configurable)
|
|
176
|
+
setEnvValue(key, value);
|
|
177
|
+
return value;
|
|
178
|
+
},
|
|
179
|
+
set: value => setEnvValue(key, value),
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
`;
|
|
183
|
+
}
|
|
99
184
|
return `
|
|
100
185
|
export { createRequire } from 'node:module';
|
|
101
186
|
import { resolve } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("import-meta-resolve")).href)};
|
|
187
|
+
${envSource}
|
|
188
|
+
export function resolveFrom(specifier, url) {
|
|
189
|
+
return resolve(\`\${specifier}\`, url);
|
|
190
|
+
}
|
|
102
191
|
export function createMeta(filename, url, dirname) {
|
|
103
|
-
return Object.assign(Object.create(null), { filename, url, dirname, main: false, resolve: specifier =>
|
|
192
|
+
return Object.assign(Object.create(null), { filename, url, dirname, main: false, resolve: specifier => resolveFrom(specifier, url), env });
|
|
104
193
|
}
|
|
105
194
|
export async function importFrom(specifier, url, options) {
|
|
106
195
|
return import(resolve(\`\${specifier}\`, url), options);
|
|
@@ -205,6 +294,25 @@ function isConfigLoaderArtifact(filepath, directory) {
|
|
|
205
294
|
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
206
295
|
}
|
|
207
296
|
/**
|
|
297
|
+
* 没有 Vite 配置时的 import.meta.env
|
|
298
|
+
*
|
|
299
|
+
* @description 只给 Vite 会在 app 代码里提供的键:前缀变量加标准键。
|
|
300
|
+
* prepare() 在 Vite 解析配置之前运行,`.env` 文件的值此时还没有人读过
|
|
301
|
+
*/
|
|
302
|
+
function fallbackConfigEnv() {
|
|
303
|
+
const env = {};
|
|
304
|
+
for (const [key, value] of Object.entries(process.env)) if (value !== void 0 && key.startsWith("VITE_")) env[key] = value;
|
|
305
|
+
const production = process.env.NODE_ENV === "production";
|
|
306
|
+
return {
|
|
307
|
+
...env,
|
|
308
|
+
BASE_URL: "/",
|
|
309
|
+
MODE: process.env.NODE_ENV ?? "development",
|
|
310
|
+
DEV: !production,
|
|
311
|
+
PROD: production,
|
|
312
|
+
SSR: false
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
208
316
|
* 页面配置加载器
|
|
209
317
|
*
|
|
210
318
|
* @description 按配置源顺序发现并加载首个有效配置,返回配置对象及依赖路径;加载失败时记录恢复路径并抛出错误
|
|
@@ -230,9 +338,47 @@ var PagesConfigLoader = class {
|
|
|
230
338
|
recoveryCandidates: [],
|
|
231
339
|
recoveryDirectories: []
|
|
232
340
|
};
|
|
233
|
-
|
|
341
|
+
/** 配置图里 import.meta.env 的值,Vite 会话就绪后可能被替换 */
|
|
342
|
+
env;
|
|
343
|
+
envDefine = {};
|
|
344
|
+
/** 是否已接收当前 Vite 会话的环境 */
|
|
345
|
+
envFromVite = false;
|
|
346
|
+
warn;
|
|
347
|
+
/** 同一文件同一成员只提示一次;watch 每轮都会重新转换所有输入 */
|
|
348
|
+
reportedMetaMembers = /* @__PURE__ */ new Set();
|
|
349
|
+
/**
|
|
350
|
+
* @param root - 项目根目录,配置入口和依赖都按它解析
|
|
351
|
+
* @param warn - 提示出口,同一文件同一成员只调用一次
|
|
352
|
+
*/
|
|
353
|
+
constructor(root, warn) {
|
|
234
354
|
this.root = root;
|
|
235
355
|
this.artifactDirectory = normalizeConfigPath(path.join(root, "node_modules/.cache/uni-pages"), root);
|
|
356
|
+
this.env = fallbackConfigEnv();
|
|
357
|
+
this.warn = warn;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* 替换配置图里 import.meta.env 的值
|
|
361
|
+
*
|
|
362
|
+
* @param env - Vite 解析后的环境值;下一轮加载生效
|
|
363
|
+
* @param define - Vite 的定义映射,只应用 import.meta.env.* 条目
|
|
364
|
+
* @returns 首次用上 Vite 的 env 时为 `true`,之前生成的 pages.json 需要重算;再次设置返回 `false`
|
|
365
|
+
*/
|
|
366
|
+
setEnv(env, define = {}) {
|
|
367
|
+
const replaced = !this.envFromVite;
|
|
368
|
+
this.env = env;
|
|
369
|
+
this.envDefine = define;
|
|
370
|
+
this.envFromVite = true;
|
|
371
|
+
return replaced;
|
|
372
|
+
}
|
|
373
|
+
/** 把成员问题转成带文件位置的提示;同一文件同一成员只报一次 */
|
|
374
|
+
reportMetaWarnings(warnings) {
|
|
375
|
+
if (!this.warn) return;
|
|
376
|
+
for (const { file, line, column, member } of warnings) {
|
|
377
|
+
const key = `${file}\u0000${member}`;
|
|
378
|
+
if (this.reportedMetaMembers.has(key)) continue;
|
|
379
|
+
this.reportedMetaMembers.add(key);
|
|
380
|
+
this.warn(`${normalizePath(path.relative(this.root, file))}:${line}:${column} reads import.meta.${member}, which is not available while the pages config runs. Read environment values from process.env, and move other Vite-only access out of the config's import graph.`);
|
|
381
|
+
}
|
|
236
382
|
}
|
|
237
383
|
/** 监听输入是一份只读快照,调用方不需要理解加载器的恢复状态 */
|
|
238
384
|
get watchInput() {
|
|
@@ -318,8 +464,10 @@ var PagesConfigLoader = class {
|
|
|
318
464
|
*/
|
|
319
465
|
async loadScript(source, code, dependencies, attempted) {
|
|
320
466
|
const sourcePath = normalizeConfigPath(source, this.root);
|
|
467
|
+
const metaWarnings = [];
|
|
321
468
|
const importDirectories = /* @__PURE__ */ new Set();
|
|
322
469
|
const recoveryCandidates = /* @__PURE__ */ new Set();
|
|
470
|
+
let bundled = false;
|
|
323
471
|
const root = this.root;
|
|
324
472
|
const cacheDirectory = this.artifactDirectory;
|
|
325
473
|
mkdirSync(cacheDirectory, { recursive: true });
|
|
@@ -327,7 +475,7 @@ var PagesConfigLoader = class {
|
|
|
327
475
|
const runtime = normalizePath(path.join(bundleDirectory, "runtime.mjs"));
|
|
328
476
|
const entry = scriptExtensions.test(source) ? source : path.join(bundleDirectory, "entry.ts");
|
|
329
477
|
try {
|
|
330
|
-
await writeFile(runtime, configRuntimeSource());
|
|
478
|
+
await writeFile(runtime, await configRuntimeSource(this.env, this.envDefine));
|
|
331
479
|
const { mod, dependencies: inputs } = await bundleRequire({
|
|
332
480
|
filepath: entry,
|
|
333
481
|
cwd: this.root,
|
|
@@ -356,6 +504,9 @@ var PagesConfigLoader = class {
|
|
|
356
504
|
plugins: [{
|
|
357
505
|
name: "uni-pages-config-inputs",
|
|
358
506
|
setup(build) {
|
|
507
|
+
build.onEnd((result) => {
|
|
508
|
+
if (result.errors.length === 0) bundled = true;
|
|
509
|
+
});
|
|
359
510
|
build.onResolve({ filter: /.*/ }, async (args) => {
|
|
360
511
|
if (args.kind === "entry-point") return { path: path.resolve(sourcePath) };
|
|
361
512
|
if (args.pluginData?.resolvingPackage) return;
|
|
@@ -399,8 +550,10 @@ var PagesConfigLoader = class {
|
|
|
399
550
|
};
|
|
400
551
|
if (!isNodeModulesPath(file) && !isConfigLoaderArtifact(file, cacheDirectory)) attempted.add(file);
|
|
401
552
|
if (file !== sourcePath && !scriptExtensions.test(file)) return;
|
|
553
|
+
const transformed = await transformConfigSource(file === sourcePath ? code : await readFile(args.path, "utf8"), path.resolve(file), runtime);
|
|
554
|
+
metaWarnings.push(...transformed.warnings);
|
|
402
555
|
return {
|
|
403
|
-
contents:
|
|
556
|
+
contents: transformed.code,
|
|
404
557
|
loader: "js"
|
|
405
558
|
};
|
|
406
559
|
});
|
|
@@ -418,12 +571,14 @@ var PagesConfigLoader = class {
|
|
|
418
571
|
}
|
|
419
572
|
return unwrapConfig(mod.default ?? mod);
|
|
420
573
|
} catch (error) {
|
|
421
|
-
if (
|
|
574
|
+
if (bundled && error instanceof Error) explainEvaluationError(error, normalizePath(path.relative(this.root, sourcePath)));
|
|
575
|
+
if (!bundled) {
|
|
422
576
|
for (const candidate of recoveryCandidates) if (!existsSync(candidate)) this.recoveryCandidates.add(candidate);
|
|
423
577
|
for (const directory of importDirectories) this.recoveryDirectories.add(directory);
|
|
424
578
|
}
|
|
425
579
|
throw error;
|
|
426
580
|
} finally {
|
|
581
|
+
this.reportMetaWarnings(metaWarnings);
|
|
427
582
|
try {
|
|
428
583
|
await rm(bundleDirectory, {
|
|
429
584
|
recursive: true,
|
|
@@ -437,6 +592,21 @@ var PagesConfigLoader = class {
|
|
|
437
592
|
}
|
|
438
593
|
}
|
|
439
594
|
};
|
|
595
|
+
/**
|
|
596
|
+
* 说明执行阶段错误的来源,并写进 message 和 stack
|
|
597
|
+
*
|
|
598
|
+
* @description 字段只读或访问器抛错时保留原异常,诊断失败不能覆盖配置错误
|
|
599
|
+
* @param error 配置执行阶段抛出的错误
|
|
600
|
+
* @param file 相对项目根的配置入口路径,用于说明错误来自哪份配置
|
|
601
|
+
*/
|
|
602
|
+
function explainEvaluationError(error, file) {
|
|
603
|
+
const note = `\n[vite-plugin-uni-pages] The error happened while evaluating the config generated from ${file} and the modules it imports; the stack above points into that temporary bundle, not into your source.`;
|
|
604
|
+
try {
|
|
605
|
+
const stack = error.stack;
|
|
606
|
+
error.message += note;
|
|
607
|
+
if (typeof stack === "string") error.stack = stack + note;
|
|
608
|
+
} catch {}
|
|
609
|
+
}
|
|
440
610
|
function unwrapConfig(value) {
|
|
441
611
|
if (value === null || typeof value !== "object" || !("default" in value) || value.default === null || typeof value.default !== "object") return value;
|
|
442
612
|
const result = value.default;
|
|
@@ -602,7 +772,7 @@ declare module "virtual:uni-pages" {
|
|
|
602
772
|
*/
|
|
603
773
|
async function writeFile$1(filePath, content) {
|
|
604
774
|
await mkdir(dirname(filePath), { recursive: true });
|
|
605
|
-
return await
|
|
775
|
+
return await writeFileAtomic(filePath, content);
|
|
606
776
|
}
|
|
607
777
|
/**
|
|
608
778
|
* 将声明文件写入磁盘
|
|
@@ -3092,7 +3262,10 @@ const TAB_BAR_PLACEHOLDER = "@@uni-pages-tab-bar-placeholder@@";
|
|
|
3092
3262
|
*/
|
|
3093
3263
|
async function writePagesJson(jsonPath, data, options) {
|
|
3094
3264
|
return withFileLock(jsonPath, async () => {
|
|
3095
|
-
const existingContent = await fs.promises.readFile(jsonPath, { encoding: "utf-8" }).catch(() =>
|
|
3265
|
+
const existingContent = await fs.promises.readFile(jsonPath, { encoding: "utf-8" }).catch((error) => {
|
|
3266
|
+
if (isMissingFsError(error)) return "";
|
|
3267
|
+
throw error;
|
|
3268
|
+
});
|
|
3096
3269
|
const content = mergePagesJson(existingContent, data, options);
|
|
3097
3270
|
if (existingContent === content) {
|
|
3098
3271
|
debug.pages("PagesJson Not have change");
|
|
@@ -3344,7 +3517,7 @@ var PageContext = class {
|
|
|
3344
3517
|
*/
|
|
3345
3518
|
constructor(userOptions, viteRoot = process.cwd(), platform$1 = platform) {
|
|
3346
3519
|
this.root = normalizePath(viteRoot);
|
|
3347
|
-
this.configLoader = new PagesConfigLoader(this.root);
|
|
3520
|
+
this.configLoader = new PagesConfigLoader(this.root, (message) => this.logger?.warn(message, { timestamp: true }));
|
|
3348
3521
|
this.configWatch = new ConfigWatchIndex(this.root, this.configLoader.artifactDirectory);
|
|
3349
3522
|
this.platform = platform$1;
|
|
3350
3523
|
debug.options("root", this.root);
|
|
@@ -3373,6 +3546,17 @@ var PageContext = class {
|
|
|
3373
3546
|
this.logger = logger;
|
|
3374
3547
|
}
|
|
3375
3548
|
/**
|
|
3549
|
+
* 设置配置图里 import.meta.env 的值
|
|
3550
|
+
*
|
|
3551
|
+
* @description 下一次配置加载时生效,不会自行触发页面生成
|
|
3552
|
+
* @param env - Vite 解析后的环境值
|
|
3553
|
+
* @param define - Vite 的定义映射,只应用 import.meta.env.* 条目
|
|
3554
|
+
* @returns 首次用上 Vite 的 env 时为 `true`,已经生成的 pages.json 需要重算
|
|
3555
|
+
*/
|
|
3556
|
+
setConfigEnv(env, define = {}) {
|
|
3557
|
+
return this.configLoader.setEnv(env, define);
|
|
3558
|
+
}
|
|
3559
|
+
/**
|
|
3376
3560
|
* 加载用户页面配置文件(如 pages.config.ts)
|
|
3377
3561
|
* 使用 unconfig 加载配置,支持多种配置文件格式
|
|
3378
3562
|
*/
|
|
@@ -4236,7 +4420,10 @@ function VitePluginUniPages(userOptions = {}) {
|
|
|
4236
4420
|
* 初始化 PageContext,设置 logger,生成初始 pages.json
|
|
4237
4421
|
*/
|
|
4238
4422
|
async configResolved(config) {
|
|
4239
|
-
const state = initialize(config.root, config.plugins.some((v) => v.name === "vite-plugin-uni-platform"), config.command
|
|
4423
|
+
const state = initialize(config.root, config.plugins.some((v) => v.name === "vite-plugin-uni-platform"), config.command, {
|
|
4424
|
+
...config.env,
|
|
4425
|
+
SSR: false
|
|
4426
|
+
}, config.define);
|
|
4240
4427
|
state.watching = config.command === "build" && !!config.build.watch;
|
|
4241
4428
|
try {
|
|
4242
4429
|
await state.promise;
|
|
@@ -4328,7 +4515,7 @@ function VitePluginUniPages(userOptions = {}) {
|
|
|
4328
4515
|
return loadVirtualModule(initialization, id);
|
|
4329
4516
|
}
|
|
4330
4517
|
};
|
|
4331
|
-
function initialize(root, platformSuffix, source) {
|
|
4518
|
+
function initialize(root, platformSuffix, source, configEnv, configDefine) {
|
|
4332
4519
|
const resolvedRoot = normalizePath(path.resolve(root));
|
|
4333
4520
|
const platform = process.env.UNI_PLATFORM;
|
|
4334
4521
|
if (!platform) throw new Error("[vite-plugin-uni-pages] UNI_PLATFORM must be set before initializing pages. Run through the uni-app CLI or set the compilation platform before calling the plugin.");
|
|
@@ -4346,10 +4533,20 @@ function VitePluginUniPages(userOptions = {}) {
|
|
|
4346
4533
|
initialization.prepared = true;
|
|
4347
4534
|
if (initialization.ready) preparedParams = params;
|
|
4348
4535
|
} else initialization.command = source;
|
|
4536
|
+
if (configEnv) {
|
|
4537
|
+
const state = initialization;
|
|
4538
|
+
state.promise = state.promise.then(async () => {
|
|
4539
|
+
if (state.closing) throw new Error("[vite-plugin-uni-pages] The pages context was closed during initialization.");
|
|
4540
|
+
if (state.context.setConfigEnv(configEnv, configDefine)) await state.context.updatePagesJSON();
|
|
4541
|
+
if (state.closing) throw new Error("[vite-plugin-uni-pages] The pages context was closed during initialization.");
|
|
4542
|
+
return plugin;
|
|
4543
|
+
});
|
|
4544
|
+
}
|
|
4349
4545
|
return initialization;
|
|
4350
4546
|
}
|
|
4351
4547
|
const context = new PageContext(userOptions, resolvedRoot, platform);
|
|
4352
4548
|
context.withUniPlatform = platformSuffix;
|
|
4549
|
+
if (configEnv) context.setConfigEnv(configEnv, configDefine);
|
|
4353
4550
|
context.setLogger(createLogger(void 0, { prefix: "[vite-plugin-uni-pages]" }));
|
|
4354
4551
|
const state = {
|
|
4355
4552
|
params,
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uni-helper/vite-plugin-uni-pages",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.6.
|
|
4
|
+
"version": "0.6.2",
|
|
5
5
|
"description": "File system based routing for uni-app applications using Vite",
|
|
6
6
|
"author": "KeJun",
|
|
7
7
|
"license": "MIT",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"@babel/generator": "^8.0.6",
|
|
54
54
|
"@babel/types": "^8.0.6",
|
|
55
55
|
"@uni-helper/uni-env": "^0.3.3",
|
|
56
|
-
"@uni-helper/uni-pages-types": "0.6.
|
|
56
|
+
"@uni-helper/uni-pages-types": "0.6.2",
|
|
57
57
|
"@vue/compiler-sfc": "~3.4.38",
|
|
58
58
|
"ast-kit": "^3.0.0",
|
|
59
59
|
"bundle-require": "^5.1.0",
|