vite-plugin-uni-inject 0.5.0 → 0.6.0

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/README.md CHANGED
@@ -1,41 +1,19 @@
1
- # vite-plugin-uni-inject
1
+ # Vite-plugin-uni-inject
2
2
 
3
- 利用 Vite 插件机制,实现自动注入代码,解放你的双手。
3
+ 一个轻量级的 uniapp 注入增强插件,旨在为 uniapp 项目提供更舒适的开发体验。
4
4
 
5
- ## 功能特点
5
+ ## 文档
6
6
 
7
- - 干净的注入任何代码,没有多余的结构。
8
- - 支持注入 `<page-meta/>` 这种只能放在页面第一个位置的标签节点。
9
- - 支持基于文件路由的 `page.json` 自动生成并注入,无需手动维护页面表。
7
+ 请阅读 [文档](https://kriac.github.io/vite-plugin-uni-inject) 了解更多使用细节。
10
8
 
11
- ## 如何使用
9
+ ## 使用
12
10
 
13
- ### 安装依赖
11
+ 如果你在开发过程中遇到了什么问题,或者有更好的建议,欢迎提交 issue 与我们讨论。
14
12
 
15
- ```bash
16
- pnpm i -D vite-plugin-uni-inject
17
- ```
13
+ ## 贡献
18
14
 
19
- ### vite.config.ts
15
+ 首先感谢你考虑为本项目做出贡献!我们欢迎社区成员的贡献,以帮助改进和扩展本项目。
20
16
 
21
- ```ts
22
- import { defineConfig } from "vite";
23
- import { uniAutoPages, uniInject } from "vite-plugin-uni-inject";
24
- import uni from "@dcloudio/vite-plugin-uni";
17
+ ## 执照
25
18
 
26
- // 如果有重写 page.json 文件的插件,请确保写在 uniInject 之前
27
- export default defineConfig(() => {
28
- return {
29
- plugins: [uniAutoPages(), uniInject(), uni()],
30
- };
31
- });
32
- ```
33
-
34
- ### 独立插件说明
35
-
36
- - `uniAutoPages(options)`:负责扫描文件路由并补全 `src/pages.json` 。
37
- - `uniInject(options)`:负责注入 `App.inject.vue`(或自定义文件)到页面文件。
38
-
39
- ## 报告错误
40
-
41
- 欢迎提交 issue 与我们讨论。
19
+ 本项目采用 MIT 许可证,详细内容请见 [LICENSE](LICENSE) 文件。
package/dist/index.cjs CHANGED
@@ -94,14 +94,18 @@ function uniInject(opts) {
94
94
  });
95
95
  let nextScriptCode = scriptCode;
96
96
  if (imports.length) {
97
- const ranges = [...imports].sort((a, b) => b.start - a.start);
97
+ const ranges = [...imports].sort((a, b) => {
98
+ return b.start - a.start;
99
+ });
98
100
  for (const { start: rangeStart, end: rangeEnd } of ranges) {
99
101
  let removeEnd = rangeEnd;
100
102
  if (nextScriptCode.startsWith("\r\n", removeEnd)) removeEnd += 2;
101
103
  else if (nextScriptCode[removeEnd] === "\n") removeEnd += 1;
102
104
  nextScriptCode = nextScriptCode.slice(0, rangeStart) + nextScriptCode.slice(removeEnd);
103
105
  }
104
- nextScriptCode = `\n${imports.map((item) => item.code).join("\n")}${nextScriptCode}`;
106
+ nextScriptCode = `\n${imports.map((item) => {
107
+ return item.code;
108
+ }).join("\n")}${nextScriptCode}`;
105
109
  }
106
110
  newCode = newCode.slice(0, start) + nextScriptCode + newCode.slice(end);
107
111
  }
@@ -138,7 +142,9 @@ function analyzeVueContent(content, filePath) {
138
142
  if (!content.includes("definePage")) return null;
139
143
  const stripRanges = [];
140
144
  const { descriptor } = (0, _vue_compiler_sfc.parse)(content);
141
- const blocks = [descriptor.scriptSetup, descriptor.script].filter((b) => Boolean(b));
145
+ const blocks = [descriptor.scriptSetup, descriptor.script].filter((b) => {
146
+ return Boolean(b);
147
+ });
142
148
  let config = null;
143
149
  for (const block of blocks) {
144
150
  const src = block.content;
@@ -156,7 +162,9 @@ function analyzeVueContent(content, filePath) {
156
162
  for (const node of ast.program.body) {
157
163
  if (typeof node.start !== "number" || typeof node.end !== "number") continue;
158
164
  if (node.type === "ImportDeclaration") {
159
- if (node.specifiers.some((s) => s.type === "ImportSpecifier" && s.imported.type === "Identifier" && s.imported.name === "definePage")) stripRanges.push({
165
+ if (node.specifiers.some((s) => {
166
+ return s.type === "ImportSpecifier" && s.imported.type === "Identifier" && s.imported.name === "definePage";
167
+ })) stripRanges.push({
160
168
  start: base + node.start,
161
169
  end: base + node.end
162
170
  });
@@ -225,7 +233,9 @@ function getPagesByFileRoute(routes, analysisMap, pagesJson, subPackageRoots) {
225
233
  const subRouteMap = /* @__PURE__ */ new Map();
226
234
  const normalizedSubRoots = subPackageRoots.map(normalizeDir);
227
235
  for (const route of routes) {
228
- const matchedRoot = normalizedSubRoots.find((root) => route.startsWith(root + "/"));
236
+ const matchedRoot = normalizedSubRoots.find((root) => {
237
+ return route.startsWith(root + "/");
238
+ });
229
239
  if (matchedRoot) {
230
240
  const list = subRouteMap.get(matchedRoot) ?? [];
231
241
  list.push(route.slice(matchedRoot.length + 1));
@@ -241,11 +251,17 @@ function getPagesByFileRoute(routes, analysisMap, pagesJson, subPackageRoots) {
241
251
  }
242
252
  return {
243
253
  ...pagesJson,
244
- pages: buildPages(mainRoutes, analysisMap, (r) => r),
245
- subPackages: normalizedSubRoots.map((root) => ({
246
- root,
247
- pages: buildPages(subRouteMap.get(root) ?? [], analysisMap, (r) => `${root}/${r}`)
248
- }))
254
+ pages: buildPages(mainRoutes, analysisMap, (r) => {
255
+ return r;
256
+ }),
257
+ subPackages: normalizedSubRoots.map((root) => {
258
+ return {
259
+ root,
260
+ pages: buildPages(subRouteMap.get(root) ?? [], analysisMap, (r) => {
261
+ return `${root}/${r}`;
262
+ })
263
+ };
264
+ })
249
265
  };
250
266
  }
251
267
  function buildRouteDts(routes) {
@@ -257,7 +273,9 @@ function buildRouteDts(routes) {
257
273
  export type ExtractPath<T extends string, Prefix extends string> = T extends \`\${Prefix}\${infer P}\` ? P : never;
258
274
 
259
275
  /** 路由路径 */
260
- export type RoutePath = ${routes.map((r) => `"/${r}"`).join(` |\n`)};
276
+ export type RoutePath = ${routes.map((r) => {
277
+ return `"/${r}"`;
278
+ }).join(` |\n`)};
261
279
 
262
280
  declare global {
263
281
  /**
@@ -267,13 +285,17 @@ declare global {
267
285
  }
268
286
  `;
269
287
  }
270
- function writeIfTextChanged(targetPath, nextContent) {
271
- const normalize = (s) => {
272
- return s.replace(/\s+/g, "").replace(/,(?=[)\]}>])/g, "").replace(/([=(<,|&?:])\|/g, "$1");
273
- };
274
- if (fs.default.existsSync(targetPath) && normalize(fs.default.readFileSync(targetPath, "utf-8")) === normalize(nextContent)) return;
288
+ function getCachePath(cacheDir, targetPath) {
289
+ const cacheName = Buffer.from(path.default.resolve(targetPath)).toString("base64url");
290
+ return path.default.join(cacheDir, "vite-plugin-uni-inject", "auto-pages", cacheName);
291
+ }
292
+ function writeFileWithCache(targetPath, nextContent, cacheDir, forceWrite = false) {
293
+ const cachePath = getCachePath(cacheDir, targetPath);
294
+ if (!forceWrite && fs.default.existsSync(targetPath) && fs.default.existsSync(cachePath) && fs.default.readFileSync(cachePath, "utf-8") === nextContent) return;
275
295
  fs.default.mkdirSync(path.default.dirname(targetPath), { recursive: true });
276
296
  fs.default.writeFileSync(targetPath, nextContent);
297
+ fs.default.mkdirSync(path.default.dirname(cachePath), { recursive: true });
298
+ fs.default.writeFileSync(cachePath, nextContent);
277
299
  }
278
300
  /**
279
301
  * 自动补全 pages.json 插件
@@ -290,11 +312,11 @@ function uniAutoPages(opts) {
290
312
  if (!pagesJson) return;
291
313
  const { routes, analysisMap } = collectFileRoutes(srcRoot, getScanDirs(mainPackage, subPackages));
292
314
  const merged = getPagesByFileRoute(routes, analysisMap, pagesJson, subPackages);
293
- writeIfTextChanged(pagesJsonPath, JSON.stringify(merged, null, 2) + "\n");
294
- if (dts) {
295
- const newDts = buildRouteDts(routes);
296
- writeIfTextChanged(path.default.join(srcRoot, dts), newDts);
297
- }
315
+ const newPagesJson = JSON.stringify(merged, null, 2) + "\n";
316
+ const dtsPath = dts ? path.default.join(srcRoot, dts) : null;
317
+ const shouldRefreshPagesJson = dtsPath ? !fs.default.existsSync(dtsPath) : false;
318
+ writeFileWithCache(pagesJsonPath, newPagesJson, config.cacheDir, shouldRefreshPagesJson);
319
+ if (dtsPath) writeFileWithCache(dtsPath, buildRouteDts(routes), config.cacheDir);
298
320
  },
299
321
  transform(code, id) {
300
322
  const pure = id.split("?")[0];
@@ -302,7 +324,9 @@ function uniAutoPages(opts) {
302
324
  const analysis = analyzeVueContent(code, pure);
303
325
  if (!analysis?.stripRanges.length) return;
304
326
  let newCode = code;
305
- const ranges = [...analysis.stripRanges].sort((a, b) => b.start - a.start);
327
+ const ranges = [...analysis.stripRanges].sort((a, b) => {
328
+ return b.start - a.start;
329
+ });
306
330
  for (const { start, end } of ranges) {
307
331
  let removeEnd = end;
308
332
  if (newCode.startsWith("\r\n", removeEnd)) removeEnd += 2;
package/dist/index.d.cts CHANGED
@@ -78,6 +78,7 @@ declare function uniAutoPages(opts?: AutoPagesPluginOptions): {
78
78
  name: string;
79
79
  enforce: "pre";
80
80
  configResolved(config: {
81
+ cacheDir: string;
81
82
  root: string;
82
83
  }): void;
83
84
  transform(code: string, id: string): {
package/dist/index.d.mts CHANGED
@@ -78,6 +78,7 @@ declare function uniAutoPages(opts?: AutoPagesPluginOptions): {
78
78
  name: string;
79
79
  enforce: "pre";
80
80
  configResolved(config: {
81
+ cacheDir: string;
81
82
  root: string;
82
83
  }): void;
83
84
  transform(code: string, id: string): {
package/dist/index.mjs CHANGED
@@ -69,14 +69,18 @@ function uniInject(opts) {
69
69
  });
70
70
  let nextScriptCode = scriptCode;
71
71
  if (imports.length) {
72
- const ranges = [...imports].sort((a, b) => b.start - a.start);
72
+ const ranges = [...imports].sort((a, b) => {
73
+ return b.start - a.start;
74
+ });
73
75
  for (const { start: rangeStart, end: rangeEnd } of ranges) {
74
76
  let removeEnd = rangeEnd;
75
77
  if (nextScriptCode.startsWith("\r\n", removeEnd)) removeEnd += 2;
76
78
  else if (nextScriptCode[removeEnd] === "\n") removeEnd += 1;
77
79
  nextScriptCode = nextScriptCode.slice(0, rangeStart) + nextScriptCode.slice(removeEnd);
78
80
  }
79
- nextScriptCode = `\n${imports.map((item) => item.code).join("\n")}${nextScriptCode}`;
81
+ nextScriptCode = `\n${imports.map((item) => {
82
+ return item.code;
83
+ }).join("\n")}${nextScriptCode}`;
80
84
  }
81
85
  newCode = newCode.slice(0, start) + nextScriptCode + newCode.slice(end);
82
86
  }
@@ -113,7 +117,9 @@ function analyzeVueContent(content, filePath) {
113
117
  if (!content.includes("definePage")) return null;
114
118
  const stripRanges = [];
115
119
  const { descriptor } = parse$1(content);
116
- const blocks = [descriptor.scriptSetup, descriptor.script].filter((b) => Boolean(b));
120
+ const blocks = [descriptor.scriptSetup, descriptor.script].filter((b) => {
121
+ return Boolean(b);
122
+ });
117
123
  let config = null;
118
124
  for (const block of blocks) {
119
125
  const src = block.content;
@@ -131,7 +137,9 @@ function analyzeVueContent(content, filePath) {
131
137
  for (const node of ast.program.body) {
132
138
  if (typeof node.start !== "number" || typeof node.end !== "number") continue;
133
139
  if (node.type === "ImportDeclaration") {
134
- if (node.specifiers.some((s) => s.type === "ImportSpecifier" && s.imported.type === "Identifier" && s.imported.name === "definePage")) stripRanges.push({
140
+ if (node.specifiers.some((s) => {
141
+ return s.type === "ImportSpecifier" && s.imported.type === "Identifier" && s.imported.name === "definePage";
142
+ })) stripRanges.push({
135
143
  start: base + node.start,
136
144
  end: base + node.end
137
145
  });
@@ -200,7 +208,9 @@ function getPagesByFileRoute(routes, analysisMap, pagesJson, subPackageRoots) {
200
208
  const subRouteMap = /* @__PURE__ */ new Map();
201
209
  const normalizedSubRoots = subPackageRoots.map(normalizeDir);
202
210
  for (const route of routes) {
203
- const matchedRoot = normalizedSubRoots.find((root) => route.startsWith(root + "/"));
211
+ const matchedRoot = normalizedSubRoots.find((root) => {
212
+ return route.startsWith(root + "/");
213
+ });
204
214
  if (matchedRoot) {
205
215
  const list = subRouteMap.get(matchedRoot) ?? [];
206
216
  list.push(route.slice(matchedRoot.length + 1));
@@ -216,11 +226,17 @@ function getPagesByFileRoute(routes, analysisMap, pagesJson, subPackageRoots) {
216
226
  }
217
227
  return {
218
228
  ...pagesJson,
219
- pages: buildPages(mainRoutes, analysisMap, (r) => r),
220
- subPackages: normalizedSubRoots.map((root) => ({
221
- root,
222
- pages: buildPages(subRouteMap.get(root) ?? [], analysisMap, (r) => `${root}/${r}`)
223
- }))
229
+ pages: buildPages(mainRoutes, analysisMap, (r) => {
230
+ return r;
231
+ }),
232
+ subPackages: normalizedSubRoots.map((root) => {
233
+ return {
234
+ root,
235
+ pages: buildPages(subRouteMap.get(root) ?? [], analysisMap, (r) => {
236
+ return `${root}/${r}`;
237
+ })
238
+ };
239
+ })
224
240
  };
225
241
  }
226
242
  function buildRouteDts(routes) {
@@ -232,7 +248,9 @@ function buildRouteDts(routes) {
232
248
  export type ExtractPath<T extends string, Prefix extends string> = T extends \`\${Prefix}\${infer P}\` ? P : never;
233
249
 
234
250
  /** 路由路径 */
235
- export type RoutePath = ${routes.map((r) => `"/${r}"`).join(` |\n`)};
251
+ export type RoutePath = ${routes.map((r) => {
252
+ return `"/${r}"`;
253
+ }).join(` |\n`)};
236
254
 
237
255
  declare global {
238
256
  /**
@@ -242,13 +260,17 @@ declare global {
242
260
  }
243
261
  `;
244
262
  }
245
- function writeIfTextChanged(targetPath, nextContent) {
246
- const normalize = (s) => {
247
- return s.replace(/\s+/g, "").replace(/,(?=[)\]}>])/g, "").replace(/([=(<,|&?:])\|/g, "$1");
248
- };
249
- if (fs.existsSync(targetPath) && normalize(fs.readFileSync(targetPath, "utf-8")) === normalize(nextContent)) return;
263
+ function getCachePath(cacheDir, targetPath) {
264
+ const cacheName = Buffer.from(path.resolve(targetPath)).toString("base64url");
265
+ return path.join(cacheDir, "vite-plugin-uni-inject", "auto-pages", cacheName);
266
+ }
267
+ function writeFileWithCache(targetPath, nextContent, cacheDir, forceWrite = false) {
268
+ const cachePath = getCachePath(cacheDir, targetPath);
269
+ if (!forceWrite && fs.existsSync(targetPath) && fs.existsSync(cachePath) && fs.readFileSync(cachePath, "utf-8") === nextContent) return;
250
270
  fs.mkdirSync(path.dirname(targetPath), { recursive: true });
251
271
  fs.writeFileSync(targetPath, nextContent);
272
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
273
+ fs.writeFileSync(cachePath, nextContent);
252
274
  }
253
275
  /**
254
276
  * 自动补全 pages.json 插件
@@ -265,11 +287,11 @@ function uniAutoPages(opts) {
265
287
  if (!pagesJson) return;
266
288
  const { routes, analysisMap } = collectFileRoutes(srcRoot, getScanDirs(mainPackage, subPackages));
267
289
  const merged = getPagesByFileRoute(routes, analysisMap, pagesJson, subPackages);
268
- writeIfTextChanged(pagesJsonPath, JSON.stringify(merged, null, 2) + "\n");
269
- if (dts) {
270
- const newDts = buildRouteDts(routes);
271
- writeIfTextChanged(path.join(srcRoot, dts), newDts);
272
- }
290
+ const newPagesJson = JSON.stringify(merged, null, 2) + "\n";
291
+ const dtsPath = dts ? path.join(srcRoot, dts) : null;
292
+ const shouldRefreshPagesJson = dtsPath ? !fs.existsSync(dtsPath) : false;
293
+ writeFileWithCache(pagesJsonPath, newPagesJson, config.cacheDir, shouldRefreshPagesJson);
294
+ if (dtsPath) writeFileWithCache(dtsPath, buildRouteDts(routes), config.cacheDir);
273
295
  },
274
296
  transform(code, id) {
275
297
  const pure = id.split("?")[0];
@@ -277,7 +299,9 @@ function uniAutoPages(opts) {
277
299
  const analysis = analyzeVueContent(code, pure);
278
300
  if (!analysis?.stripRanges.length) return;
279
301
  let newCode = code;
280
- const ranges = [...analysis.stripRanges].sort((a, b) => b.start - a.start);
302
+ const ranges = [...analysis.stripRanges].sort((a, b) => {
303
+ return b.start - a.start;
304
+ });
281
305
  for (const { start, end } of ranges) {
282
306
  let removeEnd = end;
283
307
  if (newCode.startsWith("\r\n", removeEnd)) removeEnd += 2;
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "author": "Kriac",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "version": "0.5.0",
7
+ "version": "0.6.0",
8
8
  "homepage": "https://github.com/Kriac/vite-plugin-uni-inject",
9
9
  "repository": {
10
10
  "type": "git",