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

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
@@ -3,9 +3,10 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  const path = 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');
9
10
  const unconfig = require('unconfig');
10
11
  const Debug = require('debug');
11
12
  const lodash = require('lodash');
@@ -15,6 +16,16 @@ const JSON5 = require('json5');
15
16
  const yaml = require('yaml');
16
17
  const compilerSfc = require('@vue/compiler-sfc');
17
18
 
19
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
20
+
21
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path);
22
+ const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
23
+ const chokidar__default = /*#__PURE__*/_interopDefaultCompat(chokidar);
24
+ const Debug__default = /*#__PURE__*/_interopDefaultCompat(Debug);
25
+ const fg__default = /*#__PURE__*/_interopDefaultCompat(fg);
26
+ const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
27
+ const JSON5__default = /*#__PURE__*/_interopDefaultCompat(JSON5);
28
+
18
29
  function slash(str) {
19
30
  return str.replace(/\\/g, "/");
20
31
  }
@@ -35,11 +46,11 @@ function invalidatePagesModule(server) {
35
46
  }
36
47
  }
37
48
  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")
49
+ hmr: Debug__default("vite-plugin-uni-pages:hmr"),
50
+ routeBlock: Debug__default("vite-plugin-uni-pages:routeBlock"),
51
+ options: Debug__default("vite-plugin-uni-pages:options"),
52
+ pages: Debug__default("vite-plugin-uni-pages:pages"),
53
+ error: Debug__default("vite-plugin-uni-pages:error")
43
54
  };
44
55
  function extsToGlob(extensions) {
45
56
  return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
@@ -66,7 +77,7 @@ function mergePageMetaDataArray(pageMetaData) {
66
77
  return result;
67
78
  }
68
79
  const getPagesConfigSourcePaths = async () => {
69
- return await fg("pages.config.(ts|mts|cts|js|cjs|mjs|json)", {
80
+ return await fg__default("pages.config.(ts|mts|cts|js|cjs|mjs|json)", {
70
81
  deep: 0,
71
82
  onlyFiles: true,
72
83
  absolute: true
@@ -80,6 +91,7 @@ function resolveOptions(userOptions, viteRoot) {
80
91
  outDir = "src",
81
92
  exclude = ["node_modules", ".git", "**/__*__/**"],
82
93
  routeBlockLang = "json5",
94
+ minify = false,
83
95
  onBeforeLoadUserConfig = () => {
84
96
  },
85
97
  onAfterLoadUserConfig = () => {
@@ -106,6 +118,7 @@ function resolveOptions(userOptions, viteRoot) {
106
118
  exclude,
107
119
  routeBlockLang,
108
120
  root,
121
+ minify,
109
122
  onBeforeLoadUserConfig,
110
123
  onAfterLoadUserConfig,
111
124
  onBeforeScanPages,
@@ -118,7 +131,7 @@ function resolveOptions(userOptions, viteRoot) {
118
131
  return resolvedOptions;
119
132
  }
120
133
  function resolvePageDirs(dir, root, exclude) {
121
- const dirs = fg.sync(slash(dir), {
134
+ const dirs = fg__default.sync(slash(dir), {
122
135
  ignore: exclude,
123
136
  onlyDirectories: true,
124
137
  dot: true,
@@ -131,7 +144,7 @@ function resolvePageDirs(dir, root, exclude) {
131
144
  function getPageFiles(path, options) {
132
145
  const { exclude } = options;
133
146
  const ext = extsToGlob(FILE_EXTENSIONS);
134
- const files = fg.sync(`**/*.${ext}`, {
147
+ const files = fg__default.sync(`**/*.${ext}`, {
135
148
  ignore: exclude,
136
149
  onlyFiles: true,
137
150
  cwd: path
@@ -139,11 +152,14 @@ function getPageFiles(path, options) {
139
152
  return files;
140
153
  }
141
154
  function checkPagesJsonFile(path) {
142
- if (!fs.existsSync(path))
155
+ if (!fs__default.existsSync(path)) {
143
156
  writeFileSync(path, JSON.stringify({ pages: [{ path: "" }] }, null, 2));
157
+ return false;
158
+ }
159
+ return true;
144
160
  }
145
161
  function writeFileSync(path, content) {
146
- fs.writeFileSync(path, content, { encoding: "utf-8" });
162
+ fs__default.writeFileSync(path, content, { encoding: "utf-8" });
147
163
  }
148
164
 
149
165
  async function parseSFC(code) {
@@ -169,7 +185,7 @@ function parseCustomBlock(block, filePath, options) {
169
185
  debug.routeBlock(`use ${lang} parser`);
170
186
  if (lang === "json5") {
171
187
  try {
172
- content = JSON5.parse(block.content);
188
+ content = JSON5__default.parse(block.content);
173
189
  } catch (err) {
174
190
  throw new Error(
175
191
  `Invalid JSON5 format of <${block.type}> content in ${filePath}
@@ -203,7 +219,7 @@ ${err.message}`
203
219
  }
204
220
  }
205
221
  async function getRouteBlock(path, options) {
206
- const content = fs.readFileSync(path, "utf8");
222
+ const content = fs__default.readFileSync(path, "utf8");
207
223
  const parsedSFC = await parseSFC(content);
208
224
  const blockStr = parsedSFC?.customBlocks.find((b) => b.type === "route");
209
225
  if (!blockStr)
@@ -221,7 +237,7 @@ class PageContext {
221
237
  this.root = slash(viteRoot);
222
238
  debug.options("root", this.root);
223
239
  this.options = resolveOptions(userOptions, this.root);
224
- this.resolvedPagesJSONPath = path.join(this.root, this.options.outDir, OUTPUT_NAME);
240
+ this.resolvedPagesJSONPath = path__default.join(this.root, this.options.outDir, OUTPUT_NAME);
225
241
  debug.options(this.options);
226
242
  }
227
243
  setLogger(logger) {
@@ -238,13 +254,13 @@ class PageContext {
238
254
  }
239
255
  async scanPages() {
240
256
  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));
257
+ const pagesDirPath = slash(path__default.resolve(this.options.root, dir));
258
+ const basePath = slash(path__default.join(this.options.root, this.options.outDir));
243
259
  const files = getPageFiles(pagesDirPath, this.options);
244
260
  debug.pages(dir, files);
245
261
  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))
262
+ relativePath: path__default.relative(basePath, slash(path__default.resolve(pagesDirPath, file))),
263
+ absolutePath: slash(path__default.resolve(pagesDirPath, file))
248
264
  }));
249
265
  return { dir, files: pagePaths };
250
266
  });
@@ -299,7 +315,7 @@ class PageContext {
299
315
  async parsePage(page) {
300
316
  const { relativePath, absolutePath } = page;
301
317
  const routeBlock = await getRouteBlock(absolutePath, this.options);
302
- const relativePathWithFileName = relativePath.replace(path.extname(relativePath), "");
318
+ const relativePathWithFileName = relativePath.replace(path__default.extname(relativePath), "");
303
319
  const pageMetaDatum = { path: vite.normalizePath(relativePathWithFileName), type: routeBlock?.attr.type ?? "page" };
304
320
  if (routeBlock)
305
321
  Object.assign(pageMetaDatum, routeBlock.content);
@@ -335,7 +351,7 @@ class PageContext {
335
351
  await this.mergePageMetaData();
336
352
  this.options.onAfterMergePageMetaData(this);
337
353
  this.options.onBeforeWriteFile(this);
338
- const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, 2);
354
+ const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, this.options.minify ? void 0 : 2);
339
355
  writeFileSync(this.resolvedPagesJSONPath, pagesJson);
340
356
  this.options.onAfterWriteFile(this);
341
357
  }
@@ -351,25 +367,57 @@ function defineUniPages(config) {
351
367
  return config;
352
368
  }
353
369
 
370
+ async function restart() {
371
+ return new Promise((resolve) => {
372
+ const build = child_process.spawn(process.argv.shift(), process.argv, {
373
+ cwd: process.cwd(),
374
+ detached: true,
375
+ env: process.env
376
+ });
377
+ build.stdout?.pipe(process.stdout);
378
+ build.stderr?.pipe(process.stderr);
379
+ build.on("close", (code) => {
380
+ resolve(process.exit(code));
381
+ });
382
+ });
383
+ }
354
384
  const VitePluginUniPages = (userOptions = {}) => {
355
385
  let ctx;
356
- const resolvedPagesJSONPath = path.join(process.cwd(), userOptions.outDir ?? "src", OUTPUT_NAME);
357
- checkPagesJsonFile(resolvedPagesJSONPath);
386
+ const resolvedPagesJSONPath = path__default.join(
387
+ process.cwd(),
388
+ userOptions.outDir ?? "src",
389
+ OUTPUT_NAME
390
+ );
391
+ const isValidated = checkPagesJsonFile(resolvedPagesJSONPath);
358
392
  return {
359
393
  name: "vite-plugin-uni-pages",
360
394
  enforce: "pre",
361
395
  async configResolved(config) {
362
396
  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));
397
+ const logger = vite.createLogger(void 0, {
398
+ prefix: "[vite-plugin-uni-pages]"
399
+ });
400
+ ctx.setLogger(logger);
401
+ await ctx.updatePagesJSON();
402
+ if (config.command === "build") {
403
+ if (!isValidated) {
404
+ 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.", {
405
+ timestamp: true
406
+ });
407
+ await restart();
408
+ }
409
+ if (config.build.watch)
410
+ ctx.setupWatcher(chokidar__default.watch(ctx.options.dirs));
411
+ }
367
412
  },
413
+ // Applet do not support custom route block, so we need to remove the route block here
368
414
  async transform(code, id) {
369
415
  if (!/\.vue$/.test(id))
370
416
  return null;
371
- const s = new MagicString(code.toString());
372
- const routeBlockMatches = s.original.matchAll(/<route[^>]*>([\s\S]*?)<\/route>/g);
417
+ const s = new MagicString__default(code.toString());
418
+ const routeBlockMatches = s.original.matchAll(
419
+ /<route[^>]*>([\s\S]*?)<\/route>/g
420
+ );
373
421
  for (const match of routeBlockMatches) {
374
422
  const index = match.index;
375
423
  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,7 +1,8 @@
1
1
  import path 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';
5
6
  import { loadConfig } from 'unconfig';
6
7
  import Debug from 'debug';
7
8
  import { groupBy } from 'lodash';
@@ -76,6 +77,7 @@ function resolveOptions(userOptions, viteRoot) {
76
77
  outDir = "src",
77
78
  exclude = ["node_modules", ".git", "**/__*__/**"],
78
79
  routeBlockLang = "json5",
80
+ minify = false,
79
81
  onBeforeLoadUserConfig = () => {
80
82
  },
81
83
  onAfterLoadUserConfig = () => {
@@ -102,6 +104,7 @@ function resolveOptions(userOptions, viteRoot) {
102
104
  exclude,
103
105
  routeBlockLang,
104
106
  root,
107
+ minify,
105
108
  onBeforeLoadUserConfig,
106
109
  onAfterLoadUserConfig,
107
110
  onBeforeScanPages,
@@ -135,8 +138,11 @@ function getPageFiles(path, options) {
135
138
  return files;
136
139
  }
137
140
  function checkPagesJsonFile(path) {
138
- if (!fs.existsSync(path))
141
+ if (!fs.existsSync(path)) {
139
142
  writeFileSync(path, JSON.stringify({ pages: [{ path: "" }] }, null, 2));
143
+ return false;
144
+ }
145
+ return true;
140
146
  }
141
147
  function writeFileSync(path, content) {
142
148
  fs.writeFileSync(path, content, { encoding: "utf-8" });
@@ -331,7 +337,7 @@ class PageContext {
331
337
  await this.mergePageMetaData();
332
338
  this.options.onAfterMergePageMetaData(this);
333
339
  this.options.onBeforeWriteFile(this);
334
- const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, 2);
340
+ const pagesJson = JSON.stringify({ ...this.pagesGlobConfig, pages: this.pageMetaData }, null, this.options.minify ? void 0 : 2);
335
341
  writeFileSync(this.resolvedPagesJSONPath, pagesJson);
336
342
  this.options.onAfterWriteFile(this);
337
343
  }
@@ -347,25 +353,57 @@ function defineUniPages(config) {
347
353
  return config;
348
354
  }
349
355
 
356
+ async function restart() {
357
+ return new Promise((resolve) => {
358
+ const build = spawn(process.argv.shift(), process.argv, {
359
+ cwd: process.cwd(),
360
+ detached: true,
361
+ env: process.env
362
+ });
363
+ build.stdout?.pipe(process.stdout);
364
+ build.stderr?.pipe(process.stderr);
365
+ build.on("close", (code) => {
366
+ resolve(process.exit(code));
367
+ });
368
+ });
369
+ }
350
370
  const VitePluginUniPages = (userOptions = {}) => {
351
371
  let ctx;
352
- const resolvedPagesJSONPath = path.join(process.cwd(), userOptions.outDir ?? "src", OUTPUT_NAME);
353
- checkPagesJsonFile(resolvedPagesJSONPath);
372
+ const resolvedPagesJSONPath = path.join(
373
+ process.cwd(),
374
+ userOptions.outDir ?? "src",
375
+ OUTPUT_NAME
376
+ );
377
+ const isValidated = checkPagesJsonFile(resolvedPagesJSONPath);
354
378
  return {
355
379
  name: "vite-plugin-uni-pages",
356
380
  enforce: "pre",
357
381
  async configResolved(config) {
358
382
  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));
383
+ const logger = createLogger(void 0, {
384
+ prefix: "[vite-plugin-uni-pages]"
385
+ });
386
+ ctx.setLogger(logger);
387
+ await ctx.updatePagesJSON();
388
+ if (config.command === "build") {
389
+ if (!isValidated) {
390
+ 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.", {
391
+ timestamp: true
392
+ });
393
+ await restart();
394
+ }
395
+ if (config.build.watch)
396
+ ctx.setupWatcher(chokidar.watch(ctx.options.dirs));
397
+ }
363
398
  },
399
+ // Applet do not support custom route block, so we need to remove the route block here
364
400
  async transform(code, id) {
365
401
  if (!/\.vue$/.test(id))
366
402
  return null;
367
403
  const s = new MagicString(code.toString());
368
- const routeBlockMatches = s.original.matchAll(/<route[^>]*>([\s\S]*?)<\/route>/g);
404
+ const routeBlockMatches = s.original.matchAll(
405
+ /<route[^>]*>([\s\S]*?)<\/route>/g
406
+ );
369
407
  for (const match of routeBlockMatches) {
370
408
  const index = match.index;
371
409
  const length = match[0].length;
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.1.5",
4
+ "version": "0.1.6",
5
5
  "packageManager": "pnpm@7.16.1",
6
6
  "description": "File system based routing for uni-app applications using Vite",
7
7
  "author": "KeJun",