@uni-helper/vite-plugin-uni-pages 0.2.8 → 0.2.10

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/client.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- declare module "virtual:uni-pages" {
2
- import { PageMetaDatum } from "./src/types";
3
- import { SubPackage } from "./src/config/types/index";
4
- export const pages: PageMetaDatum[];
5
- export const subPackages: SubPackage[];
1
+ declare module 'virtual:uni-pages' {
2
+ import type { PageMetaDatum } from './src/types'
3
+ import type { SubPackage } from './src/config/types/index'
4
+
5
+ export const pages: PageMetaDatum[]
6
+ export const subPackages: SubPackage[]
6
7
  }
package/dist/index.cjs CHANGED
@@ -4,35 +4,81 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  const path = require('node:path');
6
6
  const node_child_process = require('node:child_process');
7
+ const process = require('node:process');
7
8
  const vite = require('vite');
8
9
  const MagicString = require('magic-string');
9
10
  const chokidar = require('chokidar');
10
- const process$1 = require('node:process');
11
11
  const unconfig = require('unconfig');
12
- const uniEnv = require('@uni-helper/uni-env');
13
12
  const Debug = require('debug');
14
- const lodashUnified = require('lodash-unified');
15
- const fg = require('fast-glob');
16
13
  const fs = require('node:fs');
14
+ const promises = require('node:fs/promises');
15
+ const lodashUnified = require('lodash-unified');
17
16
  const JSON5 = require('json5');
18
17
  const yaml = require('yaml');
19
18
  const compilerSfc = require('@vue/compiler-sfc');
19
+ const fg = require('fast-glob');
20
20
 
21
21
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
22
22
 
23
23
  const path__default = /*#__PURE__*/_interopDefaultCompat(path);
24
+ const process__default = /*#__PURE__*/_interopDefaultCompat(process);
24
25
  const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
25
26
  const chokidar__default = /*#__PURE__*/_interopDefaultCompat(chokidar);
26
- const process__default = /*#__PURE__*/_interopDefaultCompat(process$1);
27
27
  const Debug__default = /*#__PURE__*/_interopDefaultCompat(Debug);
28
- const fg__default = /*#__PURE__*/_interopDefaultCompat(fg);
29
28
  const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
30
29
  const JSON5__default = /*#__PURE__*/_interopDefaultCompat(JSON5);
30
+ const fg__default = /*#__PURE__*/_interopDefaultCompat(fg);
31
31
 
32
32
  function slash(str) {
33
33
  return str.replace(/\\/g, "/");
34
34
  }
35
35
 
36
+ function getDeclaration(ctx) {
37
+ const subPagesPath = ctx.subPageMetaData.map((sub) => {
38
+ return sub.pages.map((v) => `"${vite.normalizePath(path.join(sub.root, v.path))}"`);
39
+ }).flat();
40
+ const tabsPagesPath = ctx.pagesGlobConfig?.tabBar?.list?.map((v) => {
41
+ return `"${v.pagePath}"`;
42
+ }) ?? [];
43
+ const allPagesPath = [...ctx.pageMetaData.filter((page) => !tabsPagesPath.includes(page.path)).map((v) => `"${v.path}"`), ...subPagesPath];
44
+ const code = `/* eslint-disable */
45
+ /* prettier-ignore */
46
+ // @ts-nocheck
47
+ // Generated by vite-plugin-uni-pages
48
+
49
+ interface NavigateToOptions {
50
+ url: ${allPagesPath.join(" |\n ")};
51
+ }
52
+ interface RedirectToOptions extends NavigateToOptions {}
53
+
54
+ interface SwitchTabOptions {
55
+ ${tabsPagesPath.length ? `url: ${tabsPagesPath.join(" | ")}` : ""}
56
+ }
57
+
58
+ type ReLaunchOptions = NavigateToOptions | SwitchTabOptions;
59
+
60
+ declare interface Uni {
61
+ navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void;
62
+ redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void;
63
+ switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void;
64
+ reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void;
65
+ }
66
+ `;
67
+ return code;
68
+ }
69
+ async function writeFile(filePath, content) {
70
+ await promises.mkdir(path.dirname(filePath), { recursive: true });
71
+ return await promises.writeFile(filePath, content, "utf-8");
72
+ }
73
+ async function writeDeclaration(ctx, filepath) {
74
+ const originalContent = fs.existsSync(filepath) ? await promises.readFile(filepath, "utf-8") : "";
75
+ const code = getDeclaration(ctx);
76
+ if (!code)
77
+ return;
78
+ if (code !== originalContent)
79
+ await writeFile(filepath, code);
80
+ }
81
+
36
82
  const MODULE_ID_VIRTUAL = "virtual:uni-pages";
37
83
  const RESOLVED_MODULE_ID_VIRTUAL = `\0${MODULE_ID_VIRTUAL}`;
38
84
  const OUTPUT_NAME = "pages.json";
@@ -121,7 +167,8 @@ const debug = {
121
167
  pages: Debug__default("vite-plugin-uni-pages:pages"),
122
168
  subPages: Debug__default("vite-plugin-uni-pages:subPages"),
123
169
  error: Debug__default("vite-plugin-uni-pages:error"),
124
- cache: Debug__default("vite-plugin-uni-pages:cache")
170
+ cache: Debug__default("vite-plugin-uni-pages:cache"),
171
+ declaration: Debug__default("vite-plugin-uni-pages:declaration")
125
172
  };
126
173
  function extsToGlob(extensions) {
127
174
  return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
@@ -130,9 +177,6 @@ function isTargetFile(path) {
130
177
  const ext = path.split(".").pop();
131
178
  return FILE_EXTENSIONS.includes(ext);
132
179
  }
133
- function isConfigFile(path) {
134
- return path.includes("pages.config");
135
- }
136
180
  function mergePageMetaDataArray(pageMetaData) {
137
181
  const pageMetaDataObj = lodashUnified.groupBy(pageMetaData, "path");
138
182
  const result = [];
@@ -147,13 +191,6 @@ function mergePageMetaDataArray(pageMetaData) {
147
191
  }
148
192
  return result;
149
193
  }
150
- async function getPagesConfigSourcePaths(configSource) {
151
- return await fg__default(configSource.map((v) => v.files).flat(), {
152
- deep: 0,
153
- onlyFiles: true,
154
- absolute: true
155
- });
156
- }
157
194
  function useCachedPages() {
158
195
  const pages = /* @__PURE__ */ new Map();
159
196
  function parseData(block) {
@@ -176,8 +213,9 @@ function useCachedPages() {
176
213
  };
177
214
  }
178
215
 
179
- function resolveOptions(userOptions, viteRoot) {
216
+ function resolveOptions(userOptions, viteRoot = process__default.cwd()) {
180
217
  const {
218
+ dts = true,
181
219
  configSource = "pages.config",
182
220
  homePage = ["pages/index", "pages/index/index"],
183
221
  mergePages = true,
@@ -210,7 +248,9 @@ function resolveOptions(userOptions, viteRoot) {
210
248
  const resolvedSubDirs = subPackages.map((dir2) => slash(dir2));
211
249
  const resolvedHomePage = typeof homePage === "string" ? [homePage] : homePage;
212
250
  const resolvedConfigSource = typeof configSource === "string" ? [{ files: configSource }] : configSource;
251
+ const resolvedDts = !dts ? false : typeof dts === "string" ? dts : path.resolve(viteRoot, "uni-pages.d.ts");
213
252
  const resolvedOptions = {
253
+ dts: resolvedDts,
214
254
  configSource: Array.isArray(resolvedConfigSource) ? resolvedConfigSource : [resolvedConfigSource],
215
255
  homePage: resolvedHomePage,
216
256
  mergePages,
@@ -277,6 +317,7 @@ class PageContext {
277
317
  constructor(userOptions, viteRoot = process__default.cwd()) {
278
318
  __publicField(this, "_server");
279
319
  __publicField(this, "pagesGlobConfig");
320
+ __publicField(this, "pagesConfigSourcePaths", []);
280
321
  __publicField(this, "pagesPath", []);
281
322
  __publicField(this, "subPagesPath", {});
282
323
  __publicField(this, "pageMetaData", []);
@@ -303,9 +344,10 @@ class PageContext {
303
344
  this.logger = logger;
304
345
  }
305
346
  async loadUserPagesConfig() {
306
- const sources = this.options.configSource;
307
- const { config } = await unconfig.loadConfig({ cwd: this.root, sources, defaults: {} });
347
+ const configSource = this.options.configSource;
348
+ const { config, sources } = await unconfig.loadConfig({ cwd: this.root, sources: configSource, defaults: {} });
308
349
  this.pagesGlobConfig = config;
350
+ this.pagesConfigSourcePaths = sources;
309
351
  debug.options(config);
310
352
  }
311
353
  async scanPages() {
@@ -331,12 +373,9 @@ class PageContext {
331
373
  this.setupWatcher(server.watcher);
332
374
  }
333
375
  async setupWatcher(watcher) {
334
- if (!uniEnv.isH5) {
335
- const configs = await getPagesConfigSourcePaths(this.options.configSource);
336
- watcher.add(configs);
337
- }
376
+ watcher.add(this.pagesConfigSourcePaths);
338
377
  const targetDirs = [...this.options.dirs, ...this.options.subPackages].map((v) => slash(path__default.resolve(this.root, v)));
339
- const isInTargetDirs = (path2) => targetDirs.some((v) => path2.startsWith(v));
378
+ const isInTargetDirs = (filePath) => targetDirs.some((v) => slash(path__default.resolve(this.root, filePath)).startsWith(v));
340
379
  watcher.on("add", async (path2) => {
341
380
  path2 = slash(path2);
342
381
  if (!isTargetFile(path2))
@@ -349,7 +388,7 @@ class PageContext {
349
388
  });
350
389
  watcher.on("change", async (path2) => {
351
390
  path2 = slash(path2);
352
- if (!isTargetFile(path2) && !isConfigFile(path2))
391
+ if (!isTargetFile(path2))
353
392
  return;
354
393
  if (!isInTargetDirs(path2))
355
394
  return;
@@ -359,6 +398,13 @@ class PageContext {
359
398
  if (await this.updatePagesJSON(path2))
360
399
  this.onUpdate();
361
400
  });
401
+ watcher.on("change", async (path2) => {
402
+ if (this.pagesConfigSourcePaths.includes(path2)) {
403
+ debug.pages(`Config source changed: ${path2}`);
404
+ if (await this.updatePagesJSON())
405
+ this.onUpdate();
406
+ }
407
+ });
362
408
  watcher.on("unlink", async (path2) => {
363
409
  path2 = slash(path2);
364
410
  if (!isTargetFile(path2))
@@ -476,6 +522,7 @@ class PageContext {
476
522
  subPackages: this.subPageMetaData
477
523
  };
478
524
  const pagesJson = JSON.stringify(data, null, this.options.minify ? void 0 : 2);
525
+ this.generateDeclaration();
479
526
  if (lsatPagesJson === pagesJson) {
480
527
  debug.pages("PagesJson Not have change");
481
528
  return false;
@@ -496,6 +543,12 @@ class PageContext {
496
543
  resolveSubRoutes() {
497
544
  return JSON.stringify(this.subPageMetaData, null, 2);
498
545
  }
546
+ generateDeclaration() {
547
+ if (!this.options.dts)
548
+ return;
549
+ debug.declaration("generating");
550
+ return writeDeclaration(this, this.options.dts);
551
+ }
499
552
  }
500
553
  function getPagePaths(dir, options) {
501
554
  const pagesDirPath = slash(path__default.resolve(options.root, dir));
@@ -515,22 +568,22 @@ function defineUniPages(config) {
515
568
 
516
569
  async function restart() {
517
570
  return new Promise((resolve) => {
518
- const build = node_child_process.spawn(process.argv.shift(), process.argv, {
519
- cwd: process.cwd(),
571
+ const build = node_child_process.spawn(process__default.argv.shift(), process__default.argv, {
572
+ cwd: process__default.cwd(),
520
573
  detached: true,
521
- env: process.env
574
+ env: process__default.env
522
575
  });
523
- build.stdout?.pipe(process.stdout);
524
- build.stderr?.pipe(process.stderr);
576
+ build.stdout?.pipe(process__default.stdout);
577
+ build.stderr?.pipe(process__default.stderr);
525
578
  build.on("close", (code) => {
526
- resolve(process.exit(code));
579
+ resolve(process__default.exit(code));
527
580
  });
528
581
  });
529
582
  }
530
583
  function VitePluginUniPages(userOptions = {}) {
531
584
  let ctx;
532
585
  const resolvedPagesJSONPath = path__default.join(
533
- process.cwd(),
586
+ process__default.cwd(),
534
587
  userOptions.outDir ?? "src",
535
588
  OUTPUT_NAME
536
589
  );
@@ -606,11 +659,9 @@ exports.default = VitePluginUniPages;
606
659
  exports.defineUniPages = defineUniPages;
607
660
  exports.extsToGlob = extsToGlob;
608
661
  exports.getPageFiles = getPageFiles;
609
- exports.getPagesConfigSourcePaths = getPagesConfigSourcePaths;
610
662
  exports.getRouteBlock = getRouteBlock;
611
663
  exports.getRouteSfcBlock = getRouteSfcBlock;
612
664
  exports.invalidatePagesModule = invalidatePagesModule;
613
- exports.isConfigFile = isConfigFile;
614
665
  exports.isTargetFile = isTargetFile;
615
666
  exports.mergePageMetaDataArray = mergePageMetaDataArray;
616
667
  exports.parseCustomBlock = parseCustomBlock;
package/dist/index.d.cts CHANGED
@@ -224,7 +224,7 @@ interface GlobalStyle {
224
224
  'app-plus'?: AppPlus;
225
225
  /**
226
226
  * 设置编译到 H5 平台的特定样式,配置项参考下方 H5
227
- * @type H5
227
+ * @type {H5}
228
228
  * @desc H5
229
229
  */
230
230
  h5?: H5;
@@ -270,7 +270,7 @@ interface GlobalStyle {
270
270
  'mp-jd'?: object;
271
271
  /**
272
272
  * 引用小程序组件,参考 小程序组件
273
- * @type Record<string, string>
273
+ * @type {Record<string, string>}
274
274
  * @desc
275
275
  */
276
276
  usingComponents?: Record<string, string>;
@@ -441,9 +441,9 @@ interface TabBar {
441
441
  blurEffect?: string;
442
442
  /**
443
443
  * tab 的列表,详见 list 属性说明,最少2个、最多5个 tab
444
- * @type TabBarItem[]
444
+ * @type {TabBarItem[]}
445
445
  */
446
- list?: TabBarItem[];
446
+ list: [TabBarItem, TabBarItem, TabBarItem?, TabBarItem?, TabBarItem?];
447
447
  /**
448
448
  * 可选值 bottom、top
449
449
  * @default "bottom"
@@ -639,6 +639,7 @@ declare function defineUniPages(config: UserPagesConfig): UserPagesConfig;
639
639
  declare class PageContext {
640
640
  private _server;
641
641
  pagesGlobConfig: PagesConfig | undefined;
642
+ pagesConfigSourcePaths: string[];
642
643
  pagesPath: PagePath[];
643
644
  subPagesPath: Record<string, PagePath[]>;
644
645
  pageMetaData: PageMetaDatum[];
@@ -665,6 +666,7 @@ declare class PageContext {
665
666
  virtualModule(): string;
666
667
  resolveRoutes(): string;
667
668
  resolveSubRoutes(): string;
669
+ generateDeclaration(): Promise<void> | undefined;
668
670
  }
669
671
 
670
672
  declare function invalidatePagesModule(server: ViteDevServer): void;
@@ -676,17 +678,16 @@ declare const debug: {
676
678
  subPages: Debug.Debugger;
677
679
  error: Debug.Debugger;
678
680
  cache: Debug.Debugger;
681
+ declaration: Debug.Debugger;
679
682
  };
680
683
  declare function extsToGlob(extensions: string[]): string;
681
684
  declare function isTargetFile(path: string): boolean;
682
- declare function isConfigFile(path: string): boolean;
683
685
  /**
684
686
  * merge page meta data array by path and assign style
685
687
  * @param pageMetaData page meta data array
686
688
  * TODO: support merge middleware
687
689
  */
688
690
  declare function mergePageMetaDataArray(pageMetaData: PageMetaDatum[]): PageMetaDatum[];
689
- declare function getPagesConfigSourcePaths(configSource: LoadConfigSource<PagesConfig>[]): Promise<string[]>;
690
691
  declare function useCachedPages(): {
691
692
  setCache: (filePath: string, routeBlock?: SFCBlock) => void;
692
693
  hasChanged: (filePath: string, routeBlock?: SFCBlock) => Promise<boolean>;
@@ -699,6 +700,14 @@ interface CustomBlock {
699
700
  type debugType = keyof typeof debug;
700
701
  type ConfigSource = string | LoadConfigSource<PagesConfig> | LoadConfigSource<PagesConfig>[];
701
702
  interface Options {
703
+ /**
704
+ * Generate TypeScript declaration for pages path
705
+ *
706
+ * Accept boolean or a path related to project root
707
+ *
708
+ * @default true
709
+ */
710
+ dts?: boolean | string;
702
711
  /**
703
712
  * Load from configs files
704
713
  *
@@ -759,12 +768,13 @@ interface Options {
759
768
  onAfterWriteFile: (ctx: PageContext) => void;
760
769
  }
761
770
  type UserOptions = Partial<Options>;
762
- interface ResolvedOptions extends Omit<Options, 'dir' | 'homePage' | 'configSource'> {
771
+ interface ResolvedOptions extends Omit<Options, 'dir' | 'homePage' | 'configSource' | 'dts'> {
763
772
  /**
764
773
  * Resolves to the `root` value from Vite config.
765
774
  * @default config.root
766
775
  */
767
776
  root: string;
777
+ dts: string | false;
768
778
  /**
769
779
  * Resolved page dirs
770
780
  */
@@ -801,7 +811,7 @@ interface SubPageMetaDatum {
801
811
  }
802
812
 
803
813
  declare const MODULE_ID_VIRTUAL = "virtual:uni-pages";
804
- declare const RESOLVED_MODULE_ID_VIRTUAL: string;
814
+ declare const RESOLVED_MODULE_ID_VIRTUAL = "\0virtual:uni-pages";
805
815
  declare const OUTPUT_NAME = "pages.json";
806
816
  declare const FILE_EXTENSIONS: string[];
807
817
 
@@ -825,4 +835,4 @@ declare function getRouteBlock(path: string, blockStr: SFCBlock | undefined, opt
825
835
 
826
836
  declare function VitePluginUniPages(userOptions?: UserOptions): Plugin;
827
837
 
828
- export { type Condition, type ConditionItem, type ConfigSource, type CustomBlock, type EasyCom, FILE_EXTENSIONS, type GlobalStyle, type IconFont, MODULE_ID_VIRTUAL, type MidButton, OUTPUT_NAME, type Options, PageContext, type PageMetaDatum, type PagePath, type PagesConfig, type PreloadRule, RESOLVED_MODULE_ID_VIRTUAL, type ResolvedOptions, type SubPackage, type SubPageMetaDatum, type TabBar, type TabBarItem, type TheWindow, type UniIdRouter, type UserOptions, type UserPagesConfig, VitePluginUniPages, checkPagesJsonFile, debug, type debugType, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getPagesConfigSourcePaths, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isConfigFile, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
838
+ export { type Condition, type ConditionItem, type ConfigSource, type CustomBlock, type EasyCom, FILE_EXTENSIONS, type GlobalStyle, type IconFont, MODULE_ID_VIRTUAL, type MidButton, OUTPUT_NAME, type Options, PageContext, type PageMetaDatum, type PagePath, type PagesConfig, type PreloadRule, RESOLVED_MODULE_ID_VIRTUAL, type ResolvedOptions, type SubPackage, type SubPageMetaDatum, type TabBar, type TabBarItem, type TheWindow, type UniIdRouter, type UserOptions, type UserPagesConfig, VitePluginUniPages, checkPagesJsonFile, debug, type debugType, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
package/dist/index.d.mts CHANGED
@@ -224,7 +224,7 @@ interface GlobalStyle {
224
224
  'app-plus'?: AppPlus;
225
225
  /**
226
226
  * 设置编译到 H5 平台的特定样式,配置项参考下方 H5
227
- * @type H5
227
+ * @type {H5}
228
228
  * @desc H5
229
229
  */
230
230
  h5?: H5;
@@ -270,7 +270,7 @@ interface GlobalStyle {
270
270
  'mp-jd'?: object;
271
271
  /**
272
272
  * 引用小程序组件,参考 小程序组件
273
- * @type Record<string, string>
273
+ * @type {Record<string, string>}
274
274
  * @desc
275
275
  */
276
276
  usingComponents?: Record<string, string>;
@@ -441,9 +441,9 @@ interface TabBar {
441
441
  blurEffect?: string;
442
442
  /**
443
443
  * tab 的列表,详见 list 属性说明,最少2个、最多5个 tab
444
- * @type TabBarItem[]
444
+ * @type {TabBarItem[]}
445
445
  */
446
- list?: TabBarItem[];
446
+ list: [TabBarItem, TabBarItem, TabBarItem?, TabBarItem?, TabBarItem?];
447
447
  /**
448
448
  * 可选值 bottom、top
449
449
  * @default "bottom"
@@ -639,6 +639,7 @@ declare function defineUniPages(config: UserPagesConfig): UserPagesConfig;
639
639
  declare class PageContext {
640
640
  private _server;
641
641
  pagesGlobConfig: PagesConfig | undefined;
642
+ pagesConfigSourcePaths: string[];
642
643
  pagesPath: PagePath[];
643
644
  subPagesPath: Record<string, PagePath[]>;
644
645
  pageMetaData: PageMetaDatum[];
@@ -665,6 +666,7 @@ declare class PageContext {
665
666
  virtualModule(): string;
666
667
  resolveRoutes(): string;
667
668
  resolveSubRoutes(): string;
669
+ generateDeclaration(): Promise<void> | undefined;
668
670
  }
669
671
 
670
672
  declare function invalidatePagesModule(server: ViteDevServer): void;
@@ -676,17 +678,16 @@ declare const debug: {
676
678
  subPages: Debug.Debugger;
677
679
  error: Debug.Debugger;
678
680
  cache: Debug.Debugger;
681
+ declaration: Debug.Debugger;
679
682
  };
680
683
  declare function extsToGlob(extensions: string[]): string;
681
684
  declare function isTargetFile(path: string): boolean;
682
- declare function isConfigFile(path: string): boolean;
683
685
  /**
684
686
  * merge page meta data array by path and assign style
685
687
  * @param pageMetaData page meta data array
686
688
  * TODO: support merge middleware
687
689
  */
688
690
  declare function mergePageMetaDataArray(pageMetaData: PageMetaDatum[]): PageMetaDatum[];
689
- declare function getPagesConfigSourcePaths(configSource: LoadConfigSource<PagesConfig>[]): Promise<string[]>;
690
691
  declare function useCachedPages(): {
691
692
  setCache: (filePath: string, routeBlock?: SFCBlock) => void;
692
693
  hasChanged: (filePath: string, routeBlock?: SFCBlock) => Promise<boolean>;
@@ -699,6 +700,14 @@ interface CustomBlock {
699
700
  type debugType = keyof typeof debug;
700
701
  type ConfigSource = string | LoadConfigSource<PagesConfig> | LoadConfigSource<PagesConfig>[];
701
702
  interface Options {
703
+ /**
704
+ * Generate TypeScript declaration for pages path
705
+ *
706
+ * Accept boolean or a path related to project root
707
+ *
708
+ * @default true
709
+ */
710
+ dts?: boolean | string;
702
711
  /**
703
712
  * Load from configs files
704
713
  *
@@ -759,12 +768,13 @@ interface Options {
759
768
  onAfterWriteFile: (ctx: PageContext) => void;
760
769
  }
761
770
  type UserOptions = Partial<Options>;
762
- interface ResolvedOptions extends Omit<Options, 'dir' | 'homePage' | 'configSource'> {
771
+ interface ResolvedOptions extends Omit<Options, 'dir' | 'homePage' | 'configSource' | 'dts'> {
763
772
  /**
764
773
  * Resolves to the `root` value from Vite config.
765
774
  * @default config.root
766
775
  */
767
776
  root: string;
777
+ dts: string | false;
768
778
  /**
769
779
  * Resolved page dirs
770
780
  */
@@ -801,7 +811,7 @@ interface SubPageMetaDatum {
801
811
  }
802
812
 
803
813
  declare const MODULE_ID_VIRTUAL = "virtual:uni-pages";
804
- declare const RESOLVED_MODULE_ID_VIRTUAL: string;
814
+ declare const RESOLVED_MODULE_ID_VIRTUAL = "\0virtual:uni-pages";
805
815
  declare const OUTPUT_NAME = "pages.json";
806
816
  declare const FILE_EXTENSIONS: string[];
807
817
 
@@ -825,4 +835,4 @@ declare function getRouteBlock(path: string, blockStr: SFCBlock | undefined, opt
825
835
 
826
836
  declare function VitePluginUniPages(userOptions?: UserOptions): Plugin;
827
837
 
828
- export { type Condition, type ConditionItem, type ConfigSource, type CustomBlock, type EasyCom, FILE_EXTENSIONS, type GlobalStyle, type IconFont, MODULE_ID_VIRTUAL, type MidButton, OUTPUT_NAME, type Options, PageContext, type PageMetaDatum, type PagePath, type PagesConfig, type PreloadRule, RESOLVED_MODULE_ID_VIRTUAL, type ResolvedOptions, type SubPackage, type SubPageMetaDatum, type TabBar, type TabBarItem, type TheWindow, type UniIdRouter, type UserOptions, type UserPagesConfig, VitePluginUniPages, checkPagesJsonFile, debug, type debugType, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getPagesConfigSourcePaths, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isConfigFile, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
838
+ export { type Condition, type ConditionItem, type ConfigSource, type CustomBlock, type EasyCom, FILE_EXTENSIONS, type GlobalStyle, type IconFont, MODULE_ID_VIRTUAL, type MidButton, OUTPUT_NAME, type Options, PageContext, type PageMetaDatum, type PagePath, type PagesConfig, type PreloadRule, RESOLVED_MODULE_ID_VIRTUAL, type ResolvedOptions, type SubPackage, type SubPageMetaDatum, type TabBar, type TabBarItem, type TheWindow, type UniIdRouter, type UserOptions, type UserPagesConfig, VitePluginUniPages, checkPagesJsonFile, debug, type debugType, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
package/dist/index.d.ts CHANGED
@@ -224,7 +224,7 @@ interface GlobalStyle {
224
224
  'app-plus'?: AppPlus;
225
225
  /**
226
226
  * 设置编译到 H5 平台的特定样式,配置项参考下方 H5
227
- * @type H5
227
+ * @type {H5}
228
228
  * @desc H5
229
229
  */
230
230
  h5?: H5;
@@ -270,7 +270,7 @@ interface GlobalStyle {
270
270
  'mp-jd'?: object;
271
271
  /**
272
272
  * 引用小程序组件,参考 小程序组件
273
- * @type Record<string, string>
273
+ * @type {Record<string, string>}
274
274
  * @desc
275
275
  */
276
276
  usingComponents?: Record<string, string>;
@@ -441,9 +441,9 @@ interface TabBar {
441
441
  blurEffect?: string;
442
442
  /**
443
443
  * tab 的列表,详见 list 属性说明,最少2个、最多5个 tab
444
- * @type TabBarItem[]
444
+ * @type {TabBarItem[]}
445
445
  */
446
- list?: TabBarItem[];
446
+ list: [TabBarItem, TabBarItem, TabBarItem?, TabBarItem?, TabBarItem?];
447
447
  /**
448
448
  * 可选值 bottom、top
449
449
  * @default "bottom"
@@ -639,6 +639,7 @@ declare function defineUniPages(config: UserPagesConfig): UserPagesConfig;
639
639
  declare class PageContext {
640
640
  private _server;
641
641
  pagesGlobConfig: PagesConfig | undefined;
642
+ pagesConfigSourcePaths: string[];
642
643
  pagesPath: PagePath[];
643
644
  subPagesPath: Record<string, PagePath[]>;
644
645
  pageMetaData: PageMetaDatum[];
@@ -665,6 +666,7 @@ declare class PageContext {
665
666
  virtualModule(): string;
666
667
  resolveRoutes(): string;
667
668
  resolveSubRoutes(): string;
669
+ generateDeclaration(): Promise<void> | undefined;
668
670
  }
669
671
 
670
672
  declare function invalidatePagesModule(server: ViteDevServer): void;
@@ -676,17 +678,16 @@ declare const debug: {
676
678
  subPages: Debug.Debugger;
677
679
  error: Debug.Debugger;
678
680
  cache: Debug.Debugger;
681
+ declaration: Debug.Debugger;
679
682
  };
680
683
  declare function extsToGlob(extensions: string[]): string;
681
684
  declare function isTargetFile(path: string): boolean;
682
- declare function isConfigFile(path: string): boolean;
683
685
  /**
684
686
  * merge page meta data array by path and assign style
685
687
  * @param pageMetaData page meta data array
686
688
  * TODO: support merge middleware
687
689
  */
688
690
  declare function mergePageMetaDataArray(pageMetaData: PageMetaDatum[]): PageMetaDatum[];
689
- declare function getPagesConfigSourcePaths(configSource: LoadConfigSource<PagesConfig>[]): Promise<string[]>;
690
691
  declare function useCachedPages(): {
691
692
  setCache: (filePath: string, routeBlock?: SFCBlock) => void;
692
693
  hasChanged: (filePath: string, routeBlock?: SFCBlock) => Promise<boolean>;
@@ -699,6 +700,14 @@ interface CustomBlock {
699
700
  type debugType = keyof typeof debug;
700
701
  type ConfigSource = string | LoadConfigSource<PagesConfig> | LoadConfigSource<PagesConfig>[];
701
702
  interface Options {
703
+ /**
704
+ * Generate TypeScript declaration for pages path
705
+ *
706
+ * Accept boolean or a path related to project root
707
+ *
708
+ * @default true
709
+ */
710
+ dts?: boolean | string;
702
711
  /**
703
712
  * Load from configs files
704
713
  *
@@ -759,12 +768,13 @@ interface Options {
759
768
  onAfterWriteFile: (ctx: PageContext) => void;
760
769
  }
761
770
  type UserOptions = Partial<Options>;
762
- interface ResolvedOptions extends Omit<Options, 'dir' | 'homePage' | 'configSource'> {
771
+ interface ResolvedOptions extends Omit<Options, 'dir' | 'homePage' | 'configSource' | 'dts'> {
763
772
  /**
764
773
  * Resolves to the `root` value from Vite config.
765
774
  * @default config.root
766
775
  */
767
776
  root: string;
777
+ dts: string | false;
768
778
  /**
769
779
  * Resolved page dirs
770
780
  */
@@ -801,7 +811,7 @@ interface SubPageMetaDatum {
801
811
  }
802
812
 
803
813
  declare const MODULE_ID_VIRTUAL = "virtual:uni-pages";
804
- declare const RESOLVED_MODULE_ID_VIRTUAL: string;
814
+ declare const RESOLVED_MODULE_ID_VIRTUAL = "\0virtual:uni-pages";
805
815
  declare const OUTPUT_NAME = "pages.json";
806
816
  declare const FILE_EXTENSIONS: string[];
807
817
 
@@ -825,4 +835,4 @@ declare function getRouteBlock(path: string, blockStr: SFCBlock | undefined, opt
825
835
 
826
836
  declare function VitePluginUniPages(userOptions?: UserOptions): Plugin;
827
837
 
828
- export { type Condition, type ConditionItem, type ConfigSource, type CustomBlock, type EasyCom, FILE_EXTENSIONS, type GlobalStyle, type IconFont, MODULE_ID_VIRTUAL, type MidButton, OUTPUT_NAME, type Options, PageContext, type PageMetaDatum, type PagePath, type PagesConfig, type PreloadRule, RESOLVED_MODULE_ID_VIRTUAL, type ResolvedOptions, type SubPackage, type SubPageMetaDatum, type TabBar, type TabBarItem, type TheWindow, type UniIdRouter, type UserOptions, type UserPagesConfig, VitePluginUniPages, checkPagesJsonFile, debug, type debugType, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getPagesConfigSourcePaths, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isConfigFile, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
838
+ export { type Condition, type ConditionItem, type ConfigSource, type CustomBlock, type EasyCom, FILE_EXTENSIONS, type GlobalStyle, type IconFont, MODULE_ID_VIRTUAL, type MidButton, OUTPUT_NAME, type Options, PageContext, type PageMetaDatum, type PagePath, type PagesConfig, type PreloadRule, RESOLVED_MODULE_ID_VIRTUAL, type ResolvedOptions, type SubPackage, type SubPageMetaDatum, type TabBar, type TabBarItem, type TheWindow, type UniIdRouter, type UserOptions, type UserPagesConfig, VitePluginUniPages, checkPagesJsonFile, debug, type debugType, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
package/dist/index.mjs CHANGED
@@ -1,23 +1,69 @@
1
- import path from 'node:path';
1
+ import path, { join, dirname, resolve } from 'node:path';
2
2
  import { spawn } from 'node:child_process';
3
+ import process from 'node:process';
3
4
  import { normalizePath, createLogger } from 'vite';
4
5
  import MagicString from 'magic-string';
5
6
  import chokidar from 'chokidar';
6
- import process$1 from 'node:process';
7
7
  import { loadConfig } from 'unconfig';
8
- import { isH5 } from '@uni-helper/uni-env';
9
8
  import Debug from 'debug';
9
+ import fs, { existsSync } from 'node:fs';
10
+ import { readFile, mkdir, writeFile as writeFile$1 } from 'node:fs/promises';
10
11
  import { groupBy } from 'lodash-unified';
11
- import fg from 'fast-glob';
12
- import fs from 'node:fs';
13
12
  import JSON5 from 'json5';
14
13
  import { parse as parse$1 } from 'yaml';
15
14
  import { parse } from '@vue/compiler-sfc';
15
+ import fg from 'fast-glob';
16
16
 
17
17
  function slash(str) {
18
18
  return str.replace(/\\/g, "/");
19
19
  }
20
20
 
21
+ function getDeclaration(ctx) {
22
+ const subPagesPath = ctx.subPageMetaData.map((sub) => {
23
+ return sub.pages.map((v) => `"${normalizePath(join(sub.root, v.path))}"`);
24
+ }).flat();
25
+ const tabsPagesPath = ctx.pagesGlobConfig?.tabBar?.list?.map((v) => {
26
+ return `"${v.pagePath}"`;
27
+ }) ?? [];
28
+ const allPagesPath = [...ctx.pageMetaData.filter((page) => !tabsPagesPath.includes(page.path)).map((v) => `"${v.path}"`), ...subPagesPath];
29
+ const code = `/* eslint-disable */
30
+ /* prettier-ignore */
31
+ // @ts-nocheck
32
+ // Generated by vite-plugin-uni-pages
33
+
34
+ interface NavigateToOptions {
35
+ url: ${allPagesPath.join(" |\n ")};
36
+ }
37
+ interface RedirectToOptions extends NavigateToOptions {}
38
+
39
+ interface SwitchTabOptions {
40
+ ${tabsPagesPath.length ? `url: ${tabsPagesPath.join(" | ")}` : ""}
41
+ }
42
+
43
+ type ReLaunchOptions = NavigateToOptions | SwitchTabOptions;
44
+
45
+ declare interface Uni {
46
+ navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void;
47
+ redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void;
48
+ switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void;
49
+ reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void;
50
+ }
51
+ `;
52
+ return code;
53
+ }
54
+ async function writeFile(filePath, content) {
55
+ await mkdir(dirname(filePath), { recursive: true });
56
+ return await writeFile$1(filePath, content, "utf-8");
57
+ }
58
+ async function writeDeclaration(ctx, filepath) {
59
+ const originalContent = existsSync(filepath) ? await readFile(filepath, "utf-8") : "";
60
+ const code = getDeclaration(ctx);
61
+ if (!code)
62
+ return;
63
+ if (code !== originalContent)
64
+ await writeFile(filepath, code);
65
+ }
66
+
21
67
  const MODULE_ID_VIRTUAL = "virtual:uni-pages";
22
68
  const RESOLVED_MODULE_ID_VIRTUAL = `\0${MODULE_ID_VIRTUAL}`;
23
69
  const OUTPUT_NAME = "pages.json";
@@ -106,7 +152,8 @@ const debug = {
106
152
  pages: Debug("vite-plugin-uni-pages:pages"),
107
153
  subPages: Debug("vite-plugin-uni-pages:subPages"),
108
154
  error: Debug("vite-plugin-uni-pages:error"),
109
- cache: Debug("vite-plugin-uni-pages:cache")
155
+ cache: Debug("vite-plugin-uni-pages:cache"),
156
+ declaration: Debug("vite-plugin-uni-pages:declaration")
110
157
  };
111
158
  function extsToGlob(extensions) {
112
159
  return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
@@ -115,9 +162,6 @@ function isTargetFile(path) {
115
162
  const ext = path.split(".").pop();
116
163
  return FILE_EXTENSIONS.includes(ext);
117
164
  }
118
- function isConfigFile(path) {
119
- return path.includes("pages.config");
120
- }
121
165
  function mergePageMetaDataArray(pageMetaData) {
122
166
  const pageMetaDataObj = groupBy(pageMetaData, "path");
123
167
  const result = [];
@@ -132,13 +176,6 @@ function mergePageMetaDataArray(pageMetaData) {
132
176
  }
133
177
  return result;
134
178
  }
135
- async function getPagesConfigSourcePaths(configSource) {
136
- return await fg(configSource.map((v) => v.files).flat(), {
137
- deep: 0,
138
- onlyFiles: true,
139
- absolute: true
140
- });
141
- }
142
179
  function useCachedPages() {
143
180
  const pages = /* @__PURE__ */ new Map();
144
181
  function parseData(block) {
@@ -161,8 +198,9 @@ function useCachedPages() {
161
198
  };
162
199
  }
163
200
 
164
- function resolveOptions(userOptions, viteRoot) {
201
+ function resolveOptions(userOptions, viteRoot = process.cwd()) {
165
202
  const {
203
+ dts = true,
166
204
  configSource = "pages.config",
167
205
  homePage = ["pages/index", "pages/index/index"],
168
206
  mergePages = true,
@@ -190,12 +228,14 @@ function resolveOptions(userOptions, viteRoot) {
190
228
  onAfterWriteFile = () => {
191
229
  }
192
230
  } = userOptions;
193
- const root = viteRoot || slash(process$1.cwd());
231
+ const root = viteRoot || slash(process.cwd());
194
232
  const resolvedDirs = resolvePageDirs(dir, root, exclude);
195
233
  const resolvedSubDirs = subPackages.map((dir2) => slash(dir2));
196
234
  const resolvedHomePage = typeof homePage === "string" ? [homePage] : homePage;
197
235
  const resolvedConfigSource = typeof configSource === "string" ? [{ files: configSource }] : configSource;
236
+ const resolvedDts = !dts ? false : typeof dts === "string" ? dts : resolve(viteRoot, "uni-pages.d.ts");
198
237
  const resolvedOptions = {
238
+ dts: resolvedDts,
199
239
  configSource: Array.isArray(resolvedConfigSource) ? resolvedConfigSource : [resolvedConfigSource],
200
240
  homePage: resolvedHomePage,
201
241
  mergePages,
@@ -259,9 +299,10 @@ var __publicField = (obj, key, value) => {
259
299
  let lsatPagesJson = "";
260
300
  const { setCache, hasChanged } = useCachedPages();
261
301
  class PageContext {
262
- constructor(userOptions, viteRoot = process$1.cwd()) {
302
+ constructor(userOptions, viteRoot = process.cwd()) {
263
303
  __publicField(this, "_server");
264
304
  __publicField(this, "pagesGlobConfig");
305
+ __publicField(this, "pagesConfigSourcePaths", []);
265
306
  __publicField(this, "pagesPath", []);
266
307
  __publicField(this, "subPagesPath", {});
267
308
  __publicField(this, "pageMetaData", []);
@@ -288,9 +329,10 @@ class PageContext {
288
329
  this.logger = logger;
289
330
  }
290
331
  async loadUserPagesConfig() {
291
- const sources = this.options.configSource;
292
- const { config } = await loadConfig({ cwd: this.root, sources, defaults: {} });
332
+ const configSource = this.options.configSource;
333
+ const { config, sources } = await loadConfig({ cwd: this.root, sources: configSource, defaults: {} });
293
334
  this.pagesGlobConfig = config;
335
+ this.pagesConfigSourcePaths = sources;
294
336
  debug.options(config);
295
337
  }
296
338
  async scanPages() {
@@ -316,12 +358,9 @@ class PageContext {
316
358
  this.setupWatcher(server.watcher);
317
359
  }
318
360
  async setupWatcher(watcher) {
319
- if (!isH5) {
320
- const configs = await getPagesConfigSourcePaths(this.options.configSource);
321
- watcher.add(configs);
322
- }
361
+ watcher.add(this.pagesConfigSourcePaths);
323
362
  const targetDirs = [...this.options.dirs, ...this.options.subPackages].map((v) => slash(path.resolve(this.root, v)));
324
- const isInTargetDirs = (path2) => targetDirs.some((v) => path2.startsWith(v));
363
+ const isInTargetDirs = (filePath) => targetDirs.some((v) => slash(path.resolve(this.root, filePath)).startsWith(v));
325
364
  watcher.on("add", async (path2) => {
326
365
  path2 = slash(path2);
327
366
  if (!isTargetFile(path2))
@@ -334,7 +373,7 @@ class PageContext {
334
373
  });
335
374
  watcher.on("change", async (path2) => {
336
375
  path2 = slash(path2);
337
- if (!isTargetFile(path2) && !isConfigFile(path2))
376
+ if (!isTargetFile(path2))
338
377
  return;
339
378
  if (!isInTargetDirs(path2))
340
379
  return;
@@ -344,6 +383,13 @@ class PageContext {
344
383
  if (await this.updatePagesJSON(path2))
345
384
  this.onUpdate();
346
385
  });
386
+ watcher.on("change", async (path2) => {
387
+ if (this.pagesConfigSourcePaths.includes(path2)) {
388
+ debug.pages(`Config source changed: ${path2}`);
389
+ if (await this.updatePagesJSON())
390
+ this.onUpdate();
391
+ }
392
+ });
347
393
  watcher.on("unlink", async (path2) => {
348
394
  path2 = slash(path2);
349
395
  if (!isTargetFile(path2))
@@ -461,6 +507,7 @@ class PageContext {
461
507
  subPackages: this.subPageMetaData
462
508
  };
463
509
  const pagesJson = JSON.stringify(data, null, this.options.minify ? void 0 : 2);
510
+ this.generateDeclaration();
464
511
  if (lsatPagesJson === pagesJson) {
465
512
  debug.pages("PagesJson Not have change");
466
513
  return false;
@@ -481,6 +528,12 @@ class PageContext {
481
528
  resolveSubRoutes() {
482
529
  return JSON.stringify(this.subPageMetaData, null, 2);
483
530
  }
531
+ generateDeclaration() {
532
+ if (!this.options.dts)
533
+ return;
534
+ debug.declaration("generating");
535
+ return writeDeclaration(this, this.options.dts);
536
+ }
484
537
  }
485
538
  function getPagePaths(dir, options) {
486
539
  const pagesDirPath = slash(path.resolve(options.root, dir));
@@ -579,4 +632,4 @@ function VitePluginUniPages(userOptions = {}) {
579
632
  };
580
633
  }
581
634
 
582
- export { FILE_EXTENSIONS, MODULE_ID_VIRTUAL, OUTPUT_NAME, PageContext, RESOLVED_MODULE_ID_VIRTUAL, VitePluginUniPages, checkPagesJsonFile, debug, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getPagesConfigSourcePaths, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isConfigFile, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
635
+ export { FILE_EXTENSIONS, MODULE_ID_VIRTUAL, OUTPUT_NAME, PageContext, RESOLVED_MODULE_ID_VIRTUAL, VitePluginUniPages, checkPagesJsonFile, debug, VitePluginUniPages as default, defineUniPages, extsToGlob, getPageFiles, getRouteBlock, getRouteSfcBlock, invalidatePagesModule, isTargetFile, mergePageMetaDataArray, parseCustomBlock, parseSFC, resolveOptions, resolvePageDirs, useCachedPages, writeFileSync };
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.2.8",
4
+ "version": "0.2.10",
5
5
  "description": "File system based routing for uni-app applications using Vite",
6
6
  "author": "KeJun",
7
7
  "license": "MIT",
@@ -15,13 +15,13 @@
15
15
  "sideEffects": false,
16
16
  "exports": {
17
17
  ".": {
18
- "require": {
19
- "types": "./dist/index.d.cts",
20
- "default": "./dist/index.cjs"
21
- },
22
18
  "import": {
23
19
  "types": "./dist/index.d.mts",
24
20
  "default": "./dist/index.mjs"
21
+ },
22
+ "require": {
23
+ "types": "./dist/index.d.cts",
24
+ "default": "./dist/index.cjs"
25
25
  }
26
26
  },
27
27
  "./client": {
@@ -45,12 +45,12 @@
45
45
  "lodash-unified": "^1.0.3",
46
46
  "magic-string": "^0.30.3",
47
47
  "unconfig": "^0.3.10",
48
- "yaml": "^2.3.1"
48
+ "yaml": "^2.3.2"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@antfu/utils": "^0.7.6",
52
52
  "@types/debug": "^4.1.8",
53
- "@types/node": "^18.17.9"
53
+ "@types/node": "^18.17.18"
54
54
  },
55
55
  "scripts": {
56
56
  "build": "unbuild",