@uni-helper/vite-plugin-uni-pages 0.1.5 → 0.1.7

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/dist/index.cjs CHANGED
@@ -2,19 +2,33 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- const path = require('path');
5
+ const path$1 = require('path');
6
+ const child_process = require('child_process');
7
+ const vite = require('vite');
6
8
  const MagicString = require('magic-string');
7
9
  const chokidar = require('chokidar');
8
- const vite = require('vite');
10
+ const path = require('node:path');
9
11
  const unconfig = require('unconfig');
12
+ const uniEnv = require('@uni-helper/uni-env');
10
13
  const Debug = require('debug');
11
- const lodash = require('lodash');
14
+ const lodashUnified = require('lodash-unified');
12
15
  const fg = require('fast-glob');
13
16
  const fs = require('fs');
14
17
  const JSON5 = require('json5');
15
18
  const yaml = require('yaml');
16
19
  const compilerSfc = require('@vue/compiler-sfc');
17
20
 
21
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
22
+
23
+ const path__default$1 = /*#__PURE__*/_interopDefaultCompat(path$1);
24
+ const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
25
+ const chokidar__default = /*#__PURE__*/_interopDefaultCompat(chokidar);
26
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path);
27
+ const Debug__default = /*#__PURE__*/_interopDefaultCompat(Debug);
28
+ const fg__default = /*#__PURE__*/_interopDefaultCompat(fg);
29
+ const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
30
+ const JSON5__default = /*#__PURE__*/_interopDefaultCompat(JSON5);
31
+
18
32
  function slash(str) {
19
33
  return str.replace(/\\/g, "/");
20
34
  }
@@ -35,11 +49,11 @@ function invalidatePagesModule(server) {
35
49
  }
36
50
  }
37
51
  const debug = {
38
- hmr: Debug("vite-plugin-uni-pages:hmr"),
39
- routeBlock: Debug("vite-plugin-uni-pages:routeBlock"),
40
- options: Debug("vite-plugin-uni-pages:options"),
41
- pages: Debug("vite-plugin-uni-pages:pages"),
42
- error: Debug("vite-plugin-uni-pages:error")
52
+ hmr: Debug__default("vite-plugin-uni-pages:hmr"),
53
+ routeBlock: Debug__default("vite-plugin-uni-pages:routeBlock"),
54
+ options: Debug__default("vite-plugin-uni-pages:options"),
55
+ pages: Debug__default("vite-plugin-uni-pages:pages"),
56
+ error: Debug__default("vite-plugin-uni-pages:error")
43
57
  };
44
58
  function extsToGlob(extensions) {
45
59
  return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
@@ -52,7 +66,7 @@ function isConfigFile(path) {
52
66
  return path.includes("pages.config");
53
67
  }
54
68
  function mergePageMetaDataArray(pageMetaData) {
55
- const pageMetaDataObj = lodash.groupBy(pageMetaData, "path");
69
+ const pageMetaDataObj = lodashUnified.groupBy(pageMetaData, "path");
56
70
  const result = [];
57
71
  for (const path in pageMetaDataObj) {
58
72
  const _pageMetaData = pageMetaDataObj[path];
@@ -66,7 +80,7 @@ function mergePageMetaDataArray(pageMetaData) {
66
80
  return result;
67
81
  }
68
82
  const getPagesConfigSourcePaths = async () => {
69
- return await fg("pages.config.(ts|mts|cts|js|cjs|mjs|json)", {
83
+ return await fg__default("pages.config.(ts|mts|cts|js|cjs|mjs|json)", {
70
84
  deep: 0,
71
85
  onlyFiles: true,
72
86
  absolute: true
@@ -80,6 +94,7 @@ function resolveOptions(userOptions, viteRoot) {
80
94
  outDir = "src",
81
95
  exclude = ["node_modules", ".git", "**/__*__/**"],
82
96
  routeBlockLang = "json5",
97
+ minify = false,
83
98
  onBeforeLoadUserConfig = () => {
84
99
  },
85
100
  onAfterLoadUserConfig = () => {
@@ -106,6 +121,7 @@ function resolveOptions(userOptions, viteRoot) {
106
121
  exclude,
107
122
  routeBlockLang,
108
123
  root,
124
+ minify,
109
125
  onBeforeLoadUserConfig,
110
126
  onAfterLoadUserConfig,
111
127
  onBeforeScanPages,
@@ -118,7 +134,7 @@ function resolveOptions(userOptions, viteRoot) {
118
134
  return resolvedOptions;
119
135
  }
120
136
  function resolvePageDirs(dir, root, exclude) {
121
- const dirs = fg.sync(slash(dir), {
137
+ const dirs = fg__default.sync(slash(dir), {
122
138
  ignore: exclude,
123
139
  onlyDirectories: true,
124
140
  dot: true,
@@ -131,7 +147,7 @@ function resolvePageDirs(dir, root, exclude) {
131
147
  function getPageFiles(path, options) {
132
148
  const { exclude } = options;
133
149
  const ext = extsToGlob(FILE_EXTENSIONS);
134
- const files = fg.sync(`**/*.${ext}`, {
150
+ const files = fg__default.sync(`**/*.${ext}`, {
135
151
  ignore: exclude,
136
152
  onlyFiles: true,
137
153
  cwd: path
@@ -139,11 +155,14 @@ function getPageFiles(path, options) {
139
155
  return files;
140
156
  }
141
157
  function checkPagesJsonFile(path) {
142
- if (!fs.existsSync(path))
158
+ if (!fs__default.existsSync(path)) {
143
159
  writeFileSync(path, JSON.stringify({ pages: [{ path: "" }] }, null, 2));
160
+ return false;
161
+ }
162
+ return true;
144
163
  }
145
164
  function writeFileSync(path, content) {
146
- fs.writeFileSync(path, content, { encoding: "utf-8" });
165
+ fs__default.writeFileSync(path, content, { encoding: "utf-8" });
147
166
  }
148
167
 
149
168
  async function parseSFC(code) {
@@ -169,7 +188,7 @@ function parseCustomBlock(block, filePath, options) {
169
188
  debug.routeBlock(`use ${lang} parser`);
170
189
  if (lang === "json5") {
171
190
  try {
172
- content = JSON5.parse(block.content);
191
+ content = JSON5__default.parse(block.content);
173
192
  } catch (err) {
174
193
  throw new Error(
175
194
  `Invalid JSON5 format of <${block.type}> content in ${filePath}
@@ -203,7 +222,7 @@ ${err.message}`
203
222
  }
204
223
  }
205
224
  async function getRouteBlock(path, options) {
206
- const content = fs.readFileSync(path, "utf8");
225
+ const content = fs__default.readFileSync(path, "utf8");
207
226
  const parsedSFC = await parseSFC(content);
208
227
  const blockStr = parsedSFC?.customBlocks.find((b) => b.type === "route");
209
228
  if (!blockStr)
@@ -221,7 +240,7 @@ class PageContext {
221
240
  this.root = slash(viteRoot);
222
241
  debug.options("root", this.root);
223
242
  this.options = resolveOptions(userOptions, this.root);
224
- this.resolvedPagesJSONPath = path.join(this.root, this.options.outDir, OUTPUT_NAME);
243
+ this.resolvedPagesJSONPath = path__default.join(this.root, this.options.outDir, OUTPUT_NAME);
225
244
  debug.options(this.options);
226
245
  }
227
246
  setLogger(logger) {
@@ -238,13 +257,13 @@ class PageContext {
238
257
  }
239
258
  async scanPages() {
240
259
  const pageDirFiles = this.options.dirs.map((dir) => {
241
- const pagesDirPath = slash(path.resolve(this.options.root, dir));
242
- const basePath = slash(path.join(this.options.root, this.options.outDir));
260
+ const pagesDirPath = slash(path__default.resolve(this.options.root, dir));
261
+ const basePath = slash(path__default.join(this.options.root, this.options.outDir));
243
262
  const files = getPageFiles(pagesDirPath, this.options);
244
263
  debug.pages(dir, files);
245
264
  const pagePaths = files.map((file) => slash(file)).map((file) => ({
246
- relativePath: path.relative(basePath, slash(path.resolve(pagesDirPath, file))),
247
- absolutePath: slash(path.resolve(pagesDirPath, file))
265
+ relativePath: path__default.relative(basePath, slash(path__default.resolve(pagesDirPath, file))),
266
+ absolutePath: slash(path__default.resolve(pagesDirPath, file))
248
267
  }));
249
268
  return { dir, files: pagePaths };
250
269
  });
@@ -258,7 +277,7 @@ class PageContext {
258
277
  this.setupWatcher(server.watcher);
259
278
  }
260
279
  async setupWatcher(watcher) {
261
- if (process.env.UNI_PLATFORM !== "h5") {
280
+ if (!uniEnv.isH5) {
262
281
  const configs = await getPagesConfigSourcePaths();
263
282
  watcher.add(configs);
264
283
  }
@@ -299,7 +318,7 @@ class PageContext {
299
318
  async parsePage(page) {
300
319
  const { relativePath, absolutePath } = page;
301
320
  const routeBlock = await getRouteBlock(absolutePath, this.options);
302
- const relativePathWithFileName = relativePath.replace(path.extname(relativePath), "");
321
+ const relativePathWithFileName = relativePath.replace(path__default.extname(relativePath), "");
303
322
  const pageMetaDatum = { path: vite.normalizePath(relativePathWithFileName), type: routeBlock?.attr.type ?? "page" };
304
323
  if (routeBlock)
305
324
  Object.assign(pageMetaDatum, routeBlock.content);
@@ -335,7 +354,7 @@ class PageContext {
335
354
  await this.mergePageMetaData();
336
355
  this.options.onAfterMergePageMetaData(this);
337
356
  this.options.onBeforeWriteFile(this);
338
- const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, 2);
357
+ const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, this.options.minify ? void 0 : 2);
339
358
  writeFileSync(this.resolvedPagesJSONPath, pagesJson);
340
359
  this.options.onAfterWriteFile(this);
341
360
  }
@@ -351,25 +370,57 @@ function defineUniPages(config) {
351
370
  return config;
352
371
  }
353
372
 
373
+ async function restart() {
374
+ return new Promise((resolve) => {
375
+ const build = child_process.spawn(process.argv.shift(), process.argv, {
376
+ cwd: process.cwd(),
377
+ detached: true,
378
+ env: process.env
379
+ });
380
+ build.stdout?.pipe(process.stdout);
381
+ build.stderr?.pipe(process.stderr);
382
+ build.on("close", (code) => {
383
+ resolve(process.exit(code));
384
+ });
385
+ });
386
+ }
354
387
  const VitePluginUniPages = (userOptions = {}) => {
355
388
  let ctx;
356
- const resolvedPagesJSONPath = path.join(process.cwd(), userOptions.outDir ?? "src", OUTPUT_NAME);
357
- checkPagesJsonFile(resolvedPagesJSONPath);
389
+ const resolvedPagesJSONPath = path__default$1.join(
390
+ process.cwd(),
391
+ userOptions.outDir ?? "src",
392
+ OUTPUT_NAME
393
+ );
394
+ const isValidated = checkPagesJsonFile(resolvedPagesJSONPath);
358
395
  return {
359
396
  name: "vite-plugin-uni-pages",
360
397
  enforce: "pre",
361
398
  async configResolved(config) {
362
399
  ctx = new PageContext(userOptions, config.root);
363
- ctx.setLogger(config.logger);
364
- ctx.updatePagesJSON();
365
- if (config.build.watch && config.command === "build")
366
- ctx.setupWatcher(chokidar.watch(ctx.options.dirs));
400
+ const logger = vite.createLogger(void 0, {
401
+ prefix: "[vite-plugin-uni-pages]"
402
+ });
403
+ ctx.setLogger(logger);
404
+ await ctx.updatePagesJSON();
405
+ if (config.command === "build") {
406
+ if (!isValidated) {
407
+ ctx.logger?.warn("In build mode, if `pages.json` does not exist, the plugin cannot create the complete `pages.json` before the uni-app, so it restarts the build.", {
408
+ timestamp: true
409
+ });
410
+ await restart();
411
+ }
412
+ if (config.build.watch)
413
+ ctx.setupWatcher(chokidar__default.watch(ctx.options.dirs));
414
+ }
367
415
  },
416
+ // Applet do not support custom route block, so we need to remove the route block here
368
417
  async transform(code, id) {
369
418
  if (!/\.vue$/.test(id))
370
419
  return null;
371
- const s = new MagicString(code.toString());
372
- const routeBlockMatches = s.original.matchAll(/<route[^>]*>([\s\S]*?)<\/route>/g);
420
+ const s = new MagicString__default(code.toString());
421
+ const routeBlockMatches = s.original.matchAll(
422
+ /<route[^>]*>([\s\S]*?)<\/route>/g
423
+ );
373
424
  for (const match of routeBlockMatches) {
374
425
  const index = match.index;
375
426
  const length = match[0].length;
package/dist/index.d.ts CHANGED
@@ -8,8 +8,11 @@ interface EasyCom {
8
8
  custom: Record<string, string>;
9
9
  }
10
10
 
11
+ type RGBColor = `rgb(${number}, ${number}, ${number})`;
12
+ type RGBAColor = `rgba(${number}, ${number}, ${number}, ${number})`;
11
13
  type HEXColor = `#${string}`;
12
14
  type ThemeColor = `@${string}`;
15
+ type Color = RGBColor | RGBAColor | HEXColor;
13
16
 
14
17
  interface AppPlus {
15
18
  /**
@@ -414,15 +417,15 @@ interface TabBar {
414
417
  /**
415
418
  * tab 上的文字默认颜色
416
419
  */
417
- color?: HEXColor;
420
+ color?: Color;
418
421
  /**
419
422
  * tab 上的文字选中时的颜色
420
423
  */
421
- selectedColor?: HEXColor;
424
+ selectedColor?: Color;
422
425
  /**
423
426
  * tab 的背景色
424
427
  */
425
- backgroundColor?: HEXColor;
428
+ backgroundColor?: Color;
426
429
  /**
427
430
  * tabbar 上边框的颜色,可选值 black/white,也支持其他颜色值
428
431
  * @default "black"
@@ -686,6 +689,11 @@ interface Options {
686
689
  * @default 'json5'
687
690
  */
688
691
  routeBlockLang: 'json5' | 'json' | 'yaml' | 'yml';
692
+ /**
693
+ * minify the `pages.json`
694
+ * @default false
695
+ */
696
+ minify: boolean;
689
697
  onBeforeLoadUserConfig: (ctx: PageContext) => void;
690
698
  onAfterLoadUserConfig: (ctx: PageContext) => void;
691
699
  onBeforeScanPages: (ctx: PageContext) => void;
@@ -756,7 +764,7 @@ declare const getPagesConfigSourcePaths: () => Promise<string[]>;
756
764
  * Resolves the files that are valid pages for the given context.
757
765
  */
758
766
  declare function getPageFiles(path: string, options: ResolvedOptions): string[];
759
- declare function checkPagesJsonFile(path: string): void;
767
+ declare function checkPagesJsonFile(path: string): boolean;
760
768
  declare function writeFileSync(path: string, content: string): void;
761
769
 
762
770
  declare function resolveOptions(userOptions: UserOptions, viteRoot?: string): ResolvedOptions;
package/dist/index.mjs CHANGED
@@ -1,10 +1,13 @@
1
- import path from 'path';
1
+ import path$1 from 'path';
2
+ import { spawn } from 'child_process';
3
+ import { normalizePath, createLogger } from 'vite';
2
4
  import MagicString from 'magic-string';
3
5
  import chokidar from 'chokidar';
4
- import { normalizePath } from 'vite';
6
+ import path from 'node:path';
5
7
  import { loadConfig } from 'unconfig';
8
+ import { isH5 } from '@uni-helper/uni-env';
6
9
  import Debug from 'debug';
7
- import { groupBy } from 'lodash';
10
+ import { groupBy } from 'lodash-unified';
8
11
  import fg from 'fast-glob';
9
12
  import fs from 'fs';
10
13
  import JSON5 from 'json5';
@@ -76,6 +79,7 @@ function resolveOptions(userOptions, viteRoot) {
76
79
  outDir = "src",
77
80
  exclude = ["node_modules", ".git", "**/__*__/**"],
78
81
  routeBlockLang = "json5",
82
+ minify = false,
79
83
  onBeforeLoadUserConfig = () => {
80
84
  },
81
85
  onAfterLoadUserConfig = () => {
@@ -102,6 +106,7 @@ function resolveOptions(userOptions, viteRoot) {
102
106
  exclude,
103
107
  routeBlockLang,
104
108
  root,
109
+ minify,
105
110
  onBeforeLoadUserConfig,
106
111
  onAfterLoadUserConfig,
107
112
  onBeforeScanPages,
@@ -135,8 +140,11 @@ function getPageFiles(path, options) {
135
140
  return files;
136
141
  }
137
142
  function checkPagesJsonFile(path) {
138
- if (!fs.existsSync(path))
143
+ if (!fs.existsSync(path)) {
139
144
  writeFileSync(path, JSON.stringify({ pages: [{ path: "" }] }, null, 2));
145
+ return false;
146
+ }
147
+ return true;
140
148
  }
141
149
  function writeFileSync(path, content) {
142
150
  fs.writeFileSync(path, content, { encoding: "utf-8" });
@@ -254,7 +262,7 @@ class PageContext {
254
262
  this.setupWatcher(server.watcher);
255
263
  }
256
264
  async setupWatcher(watcher) {
257
- if (process.env.UNI_PLATFORM !== "h5") {
265
+ if (!isH5) {
258
266
  const configs = await getPagesConfigSourcePaths();
259
267
  watcher.add(configs);
260
268
  }
@@ -331,7 +339,7 @@ class PageContext {
331
339
  await this.mergePageMetaData();
332
340
  this.options.onAfterMergePageMetaData(this);
333
341
  this.options.onBeforeWriteFile(this);
334
- const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, 2);
342
+ const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, this.options.minify ? void 0 : 2);
335
343
  writeFileSync(this.resolvedPagesJSONPath, pagesJson);
336
344
  this.options.onAfterWriteFile(this);
337
345
  }
@@ -347,25 +355,57 @@ function defineUniPages(config) {
347
355
  return config;
348
356
  }
349
357
 
358
+ async function restart() {
359
+ return new Promise((resolve) => {
360
+ const build = spawn(process.argv.shift(), process.argv, {
361
+ cwd: process.cwd(),
362
+ detached: true,
363
+ env: process.env
364
+ });
365
+ build.stdout?.pipe(process.stdout);
366
+ build.stderr?.pipe(process.stderr);
367
+ build.on("close", (code) => {
368
+ resolve(process.exit(code));
369
+ });
370
+ });
371
+ }
350
372
  const VitePluginUniPages = (userOptions = {}) => {
351
373
  let ctx;
352
- const resolvedPagesJSONPath = path.join(process.cwd(), userOptions.outDir ?? "src", OUTPUT_NAME);
353
- checkPagesJsonFile(resolvedPagesJSONPath);
374
+ const resolvedPagesJSONPath = path$1.join(
375
+ process.cwd(),
376
+ userOptions.outDir ?? "src",
377
+ OUTPUT_NAME
378
+ );
379
+ const isValidated = checkPagesJsonFile(resolvedPagesJSONPath);
354
380
  return {
355
381
  name: "vite-plugin-uni-pages",
356
382
  enforce: "pre",
357
383
  async configResolved(config) {
358
384
  ctx = new PageContext(userOptions, config.root);
359
- ctx.setLogger(config.logger);
360
- ctx.updatePagesJSON();
361
- if (config.build.watch && config.command === "build")
362
- ctx.setupWatcher(chokidar.watch(ctx.options.dirs));
385
+ const logger = createLogger(void 0, {
386
+ prefix: "[vite-plugin-uni-pages]"
387
+ });
388
+ ctx.setLogger(logger);
389
+ await ctx.updatePagesJSON();
390
+ if (config.command === "build") {
391
+ if (!isValidated) {
392
+ ctx.logger?.warn("In build mode, if `pages.json` does not exist, the plugin cannot create the complete `pages.json` before the uni-app, so it restarts the build.", {
393
+ timestamp: true
394
+ });
395
+ await restart();
396
+ }
397
+ if (config.build.watch)
398
+ ctx.setupWatcher(chokidar.watch(ctx.options.dirs));
399
+ }
363
400
  },
401
+ // Applet do not support custom route block, so we need to remove the route block here
364
402
  async transform(code, id) {
365
403
  if (!/\.vue$/.test(id))
366
404
  return null;
367
405
  const s = new MagicString(code.toString());
368
- const routeBlockMatches = s.original.matchAll(/<route[^>]*>([\s\S]*?)<\/route>/g);
406
+ const routeBlockMatches = s.original.matchAll(
407
+ /<route[^>]*>([\s\S]*?)<\/route>/g
408
+ );
369
409
  for (const match of routeBlockMatches) {
370
410
  const index = match.index;
371
411
  const length = match[0].length;
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "@uni-helper/vite-plugin-uni-pages",
3
3
  "type": "module",
4
- "version": "0.1.5",
5
- "packageManager": "pnpm@7.16.1",
4
+ "version": "0.1.7",
6
5
  "description": "File system based routing for uni-app applications using Vite",
7
6
  "author": "KeJun",
8
7
  "license": "MIT",
@@ -32,22 +31,22 @@
32
31
  "client.d.ts"
33
32
  ],
34
33
  "dependencies": {
35
- "@vue/compiler-sfc": "^3.2.45",
34
+ "@uni-helper/uni-env": "^0.0.2",
35
+ "@vue/compiler-sfc": "^3.2.47",
36
36
  "chokidar": "^3.5.3",
37
37
  "debug": "^4.3.4",
38
38
  "fast-glob": "^3.2.12",
39
39
  "json5": "^2.2.3",
40
- "lodash": "^4.17.21",
41
- "magic-string": "^0.27.0",
40
+ "lodash-unified": "^1.0.3",
41
+ "magic-string": "^0.30.0",
42
42
  "unconfig": "^0.3.7",
43
43
  "yaml": "^2.2.1"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@antfu/utils": "^0.7.2",
47
47
  "@types/debug": "^4.1.7",
48
- "@types/lodash": "^4.14.191",
49
- "@types/node": "^18.11.18",
50
- "vite": "^4.0.3"
48
+ "@types/node": "^18.15.11",
49
+ "vite": "^4.2.1"
51
50
  },
52
51
  "scripts": {
53
52
  "build": "unbuild",