@uni-helper/vite-plugin-uni-pages 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,75 @@
1
1
  # @uni-helper/vite-plugin-uni-pages
2
2
 
3
- **WIP** File system based routing for uni-app applications using Vite
3
+ **WIP** 在 Vite 驱动的 uni-app 上使用基于文件的路由系统
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ pnpm i -D @uni-helper/vite-plugin-uni-pages
9
+ ```
10
+
11
+ ## 使用
12
+
13
+ ```ts
14
+ // vite.config.ts
15
+ import { defineConfig } from "vite";
16
+ import Uni from "@dcloudio/vite-plugin-uni";
17
+ import UniPages from "@uni-helper/vite-plugin-uni-pages";
18
+ // 推荐放置在 Uni 前面
19
+ export default defineConfig({
20
+ plugins: [UniPages(), Uni()],
21
+ });
22
+ ```
23
+
24
+ 定义全局属性
25
+
26
+ ```ts
27
+ // pages.config.ts
28
+ import { definePages } from "@uni-helper/vite-plugin-uni-pages/config";
29
+
30
+ export default definePages({
31
+ // 你也可以指定 pages,内容将会被合并
32
+ pages: []
33
+ globalStyle: {
34
+ navigationBarTextStyle: "black",
35
+ navigationBarTitleText: "@uni-helper",
36
+ navigationBarBackgroundColor: "#F8F8F8",
37
+ backgroundColor: "#F8F8F8",
38
+ },
39
+ });
40
+ ```
41
+
42
+ 现在所有的 pages 将会被自动发现!
43
+
44
+ 你可以在页面中使用 route block 来指定元数据
45
+
46
+ ```vue
47
+ <!-- index.vue -->
48
+ <route lang="json" type="home">
49
+ {
50
+ "style": { "navigationBarTitleText": "@uni-helper" }
51
+ }
52
+ </route>
53
+
54
+ <!-- other.vue -->
55
+ <route lang="json">
56
+ {
57
+ "style": { "navigationBarTitleText": "@uni-helper" },
58
+ "any-meta-data": "hello"
59
+ }
60
+ </route>
61
+ ```
62
+
63
+ 导入虚拟模块即可访问所有页面的 meta-data
64
+
65
+ ```ts
66
+ /// <reference types="@uni-helper/vite-plugin-uni-pages/client" />
67
+ import { pages } from "virtual:uni-pages";
68
+ ```
4
69
 
5
70
  ## TODO
6
71
 
7
- - [ ] only update change page
8
- - [ ] middleware
9
- - [ ] pages [type](./src/config/types.ts)
72
+ - [ ] only update the changed page
73
+ - [ ] ~~middleware~~
74
+ - vite-plugin-uni-middleware
75
+ - [ ] pages [type](./src/config/types.ts)
package/client.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ declare module "virtual:uni-pages" {
2
+ export const pages: {
3
+ path: string;
4
+ type: "home" | "page";
5
+ style: any;
6
+ }[];
7
+ }
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/config/index.ts
21
+ var config_exports = {};
22
+ __export(config_exports, {
23
+ definePages: () => definePages
24
+ });
25
+ module.exports = __toCommonJS(config_exports);
26
+ function definePages(config) {
27
+ return config;
28
+ }
29
+ // Annotate the CommonJS export names for ESM import in node:
30
+ 0 && (module.exports = {
31
+ definePages
32
+ });
33
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["import { UserPagesConfig } from \"./types\";\nexport * from \"./types\";\nexport function definePages(config: UserPagesConfig) {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,SAAS,YAAY,QAAyB;AACnD,SAAO;AACT;","names":[]}
@@ -0,0 +1,20 @@
1
+ interface PagesConfig {
2
+ pages: any;
3
+ globalStyle: any;
4
+ easycom: any;
5
+ tabBar: any;
6
+ condition: any;
7
+ subPackages: any;
8
+ preloadRule: any;
9
+ workers: any;
10
+ leftWindow: any;
11
+ topWindow: any;
12
+ rightWindow: any;
13
+ uniIdRouter: any;
14
+ }
15
+ interface UserPagesConfig extends Partial<PagesConfig> {
16
+ }
17
+
18
+ declare function definePages(config: UserPagesConfig): UserPagesConfig;
19
+
20
+ export { PagesConfig, UserPagesConfig, definePages };
@@ -0,0 +1,8 @@
1
+ // src/config/index.ts
2
+ function definePages(config) {
3
+ return config;
4
+ }
5
+ export {
6
+ definePages
7
+ };
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["import { UserPagesConfig } from \"./types\";\nexport * from \"./types\";\nexport function definePages(config: UserPagesConfig) {\n return config;\n}\n"],"mappings":";AAEO,SAAS,YAAY,QAAyB;AACnD,SAAO;AACT;","names":[]}
package/dist/index.cjs CHANGED
@@ -1,156 +1,231 @@
1
- 'use strict';
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
2
25
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
26
+ // src/index.ts
27
+ var src_exports = {};
28
+ __export(src_exports, {
29
+ VitePluginUniPages: () => VitePluginUniPages,
30
+ default: () => src_default,
31
+ definePages: () => definePages
32
+ });
33
+ module.exports = __toCommonJS(src_exports);
34
+ var import_vite3 = require("vite");
4
35
 
5
- const vite = require('vite');
6
- const unconfig = require('unconfig');
7
- const path = require('path');
8
- const fs = require('fs');
9
- const fg = require('fast-glob');
10
- const compilerDom = require('@vue/compiler-dom');
11
- const jsoncParser = require('jsonc-parser');
12
- const defu = require('defu');
36
+ // src/utils.ts
37
+ var import_path = require("path");
38
+ var import_vite = require("vite");
39
+ var isPagePath = (path, options) => {
40
+ const dirPath = (0, import_path.resolve)(process.cwd(), options.pagesDir);
41
+ const filter = (0, import_vite.createFilter)(dirPath + "/**/*.(vue|nvue)");
42
+ return filter(path);
43
+ };
13
44
 
14
- const isPagePath = (path$1, options) => {
15
- const dirPath = path.resolve(process.cwd(), options.pagesDir);
16
- const filter = vite.createFilter(dirPath + "/**/*.(vue|nvue)");
17
- return filter(path$1);
45
+ // src/constant.ts
46
+ var virtualModuleId = "virtual:uni-pages";
47
+ var resolvedVirtualModuleId = "\0" + virtualModuleId;
48
+
49
+ // src/context/index.ts
50
+ var import_path2 = require("path");
51
+ var import_unconfig = require("unconfig");
52
+ var import_vite2 = require("vite");
53
+ var import_fast_glob = __toESM(require("fast-glob"), 1);
54
+ var import_jsonc_parser = require("jsonc-parser");
55
+ var import_compiler_dom = require("@vue/compiler-dom");
56
+ var import_fs = __toESM(require("fs"), 1);
57
+ var import_defu = require("defu");
58
+ var Context = class {
59
+ constructor(options) {
60
+ this.pagesPathInfo = [];
61
+ this.pagesMeta = [];
62
+ this.options = options;
63
+ this.createOrUpdatePagesJSON();
64
+ }
65
+ async loadUserPagesConfig() {
66
+ const { config } = await (0, import_unconfig.loadConfig)({
67
+ sources: [
68
+ {
69
+ files: this.options.entry,
70
+ extensions: [this.options.extension]
71
+ }
72
+ ],
73
+ merge: false
74
+ });
75
+ this.pagesConfig = config;
76
+ }
77
+ async scanPages() {
78
+ const files = await (0, import_fast_glob.default)("**/*.(vue|nvue)", {
79
+ ignore: ["node_modules", ".git", "**/__*__/*"],
80
+ onlyFiles: true,
81
+ cwd: (0, import_path2.resolve)(process.cwd(), this.options.pagesDir)
82
+ });
83
+ const basePath = (0, import_path2.relative)(
84
+ (0, import_path2.resolve)(process.cwd(), this.options.outDir),
85
+ this.options.pagesDir
86
+ );
87
+ this.pagesPathInfo = files.map((file) => {
88
+ return {
89
+ relative: (0, import_vite2.normalizePath)((0, import_path2.join)(basePath, file)),
90
+ absolute: (0, import_vite2.normalizePath)(
91
+ (0, import_path2.resolve)(process.cwd(), this.options.pagesDir, file)
92
+ )
93
+ };
94
+ });
95
+ }
96
+ async parsePage({ relative: relative2, absolute }) {
97
+ const code = await import_fs.default.promises.readFile(absolute, {
98
+ encoding: "utf-8"
99
+ });
100
+ const t = (0, import_compiler_dom.parse)(code);
101
+ const path = relative2.replace((0, import_path2.extname)(relative2), "");
102
+ let pageMeta = {
103
+ path,
104
+ type: "page"
105
+ };
106
+ t == null ? void 0 : t.children.forEach((v) => {
107
+ var _a;
108
+ if (v.type !== 1) {
109
+ return;
110
+ }
111
+ if (v.tag === "route") {
112
+ v.props.forEach((prop) => {
113
+ var _a2;
114
+ if (prop.type === 6 && prop.name === "type") {
115
+ pageMeta.type = ((_a2 = prop.value) == null ? void 0 : _a2.content) ?? pageMeta.type;
116
+ }
117
+ });
118
+ const astContent = (_a = v.children) == null ? void 0 : _a[0];
119
+ if (astContent && astContent.type === 2) {
120
+ const _pageMeta = (0, import_jsonc_parser.parse)(astContent.content);
121
+ Object.keys(_pageMeta).forEach((key) => {
122
+ pageMeta[key] = _pageMeta[key];
123
+ });
124
+ pageMeta["path"] = path;
125
+ }
126
+ }
127
+ });
128
+ return pageMeta;
129
+ }
130
+ async mergePagesMeta() {
131
+ var _a;
132
+ const pagesMeta = await Promise.all(
133
+ (_a = this.pagesPathInfo) == null ? void 0 : _a.map(async (page) => await this.parsePage(page))
134
+ );
135
+ const pages = Object.values((0, import_defu.defu)({}, pagesMeta, this.pagesConfig.pages));
136
+ pages.sort((a) => a.type === "home" ? -1 : 0);
137
+ this.pagesMeta = pages;
138
+ }
139
+ async createOrUpdatePagesJSON() {
140
+ const outputName = "pages.json";
141
+ const resolvedOutput = (0, import_vite2.normalizePath)(
142
+ (0, import_path2.resolve)(process.cwd(), this.options.outDir, outputName)
143
+ );
144
+ if (!import_fs.default.existsSync(resolvedOutput)) {
145
+ import_fs.default.writeFileSync(resolvedOutput, `{"pages": [{"path": ""}]}`, {
146
+ encoding: "utf-8"
147
+ });
148
+ }
149
+ await this.loadUserPagesConfig();
150
+ await this.scanPages();
151
+ await this.mergePagesMeta();
152
+ import_fs.default.writeFileSync(
153
+ resolvedOutput,
154
+ JSON.stringify({
155
+ ...this.pagesConfig,
156
+ pages: this.pagesMeta
157
+ }),
158
+ {
159
+ encoding: "utf-8"
160
+ }
161
+ );
162
+ }
163
+ async virtualModule() {
164
+ return `export const pages = ${JSON.stringify(this.pagesMeta)};`;
165
+ }
166
+ get pagesConfigSourcePath() {
167
+ return (0, import_vite2.normalizePath)(
168
+ (0, import_path2.resolve)(process.cwd(), `${this.options.entry}.${this.options.extension}`)
169
+ );
170
+ }
18
171
  };
19
172
 
173
+ // src/config/index.ts
20
174
  function definePages(config) {
21
175
  return config;
22
176
  }
23
177
 
24
- function defineMiddleware(middleware) {
25
- return middleware;
26
- }
27
-
178
+ // src/index.ts
28
179
  function resolveOptions(userOptions) {
29
180
  return {
30
181
  pagesDir: "src/pages",
31
182
  outDir: "src",
32
183
  entry: "pages.config",
33
184
  extension: "ts",
185
+ middlewaresDir: "src/middlewares",
34
186
  ...userOptions
35
187
  };
36
188
  }
37
- const loadUserPagesConfig = async (options) => {
38
- const { config } = await unconfig.loadConfig({
39
- sources: [
40
- {
41
- files: options.entry,
42
- extensions: [options.extension]
43
- }
44
- ],
45
- merge: false
46
- });
47
- return config;
48
- };
49
- const scanPages = async (options) => {
50
- const files = await fg("**/*.(vue|nvue)", {
51
- ignore: ["node_modules", ".git", "**/__*__/*"],
52
- onlyFiles: true,
53
- cwd: path.resolve(process.cwd(), options.pagesDir)
54
- });
55
- const basePath = path.relative(
56
- path.resolve(process.cwd(), options.outDir),
57
- options.pagesDir
58
- );
59
- return files.map((file) => {
60
- return {
61
- relative: vite.normalizePath(path.join(basePath, file)),
62
- absolute: vite.normalizePath(path.resolve(process.cwd(), options.pagesDir, file))
63
- };
64
- });
65
- };
66
- const parsePage = async ({
67
- relative: relative2,
68
- absolute
69
- }) => {
70
- const code = await fs.promises.readFile(absolute, {
71
- encoding: "utf-8"
72
- });
73
- const t = compilerDom.parse(code);
74
- const path$1 = relative2.replace(path.extname(relative2), "");
75
- let pageMeta = {
76
- path: path$1,
77
- type: "page"
78
- };
79
- t?.children.forEach((v) => {
80
- if (v.type !== 1) {
81
- return;
82
- }
83
- if (v.tag === "route") {
84
- v.props.forEach((prop) => {
85
- if (prop.type === 6 && prop.name === "type") {
86
- pageMeta.type = prop.value?.content ?? pageMeta.type;
87
- }
88
- });
89
- const astContent = v.children?.[0];
90
- if (astContent && astContent.type === 2) {
91
- const _pageMeta = jsoncParser.parse(astContent.content);
92
- Object.keys(_pageMeta).forEach((key) => {
93
- pageMeta[key] = _pageMeta[key];
94
- });
95
- pageMeta["path"] = path$1;
96
- }
97
- }
98
- });
99
- return pageMeta;
100
- };
101
- const createOrUpdatePagesJSON = async (options, path$1) => {
102
- const outputName = "pages.json";
103
- const resolvedOutput = vite.normalizePath(
104
- path.resolve(process.cwd(), options.outDir, outputName)
105
- );
106
- if (!fs.existsSync(resolvedOutput)) {
107
- fs.writeFileSync(resolvedOutput, "{}", {
108
- encoding: "utf-8"
109
- });
110
- }
111
- const config = await loadUserPagesConfig(options);
112
- const pagesPathList = await scanPages(options);
113
- const pagesMeta = await Promise.all(
114
- pagesPathList.map(async (page) => await parsePage(page))
115
- );
116
- const pages = Object.values(defu.defu({}, pagesMeta, config.pages));
117
- pages.sort((a) => a.type === "home" ? -1 : 0);
118
- config.pages = pages;
119
- fs.writeFileSync(resolvedOutput, JSON.stringify(config), {
120
- encoding: "utf-8"
121
- });
122
- };
123
- const VitePluginUniPages = async (userOptions = {}) => {
189
+ var VitePluginUniPages = async (userOptions = {}) => {
124
190
  const options = resolveOptions(userOptions);
125
- const pagesConfigSource = vite.normalizePath(
126
- path.resolve(process.cwd(), `${options.entry}.${options.extension}`)
127
- );
128
- await createOrUpdatePagesJSON(options);
191
+ const ctx = new Context(options);
129
192
  return {
130
193
  name: "vite-plugin-uni-pages",
131
194
  enforce: "pre",
132
195
  configureServer({ watcher }) {
133
- watcher.add(pagesConfigSource);
196
+ watcher.add(ctx.pagesConfigSourcePath);
134
197
  watcher.on("change", async (path) => {
135
- if (vite.normalizePath(path) === pagesConfigSource || isPagePath(path, options)) {
136
- await createOrUpdatePagesJSON(options);
198
+ if ((0, import_vite3.normalizePath)(path) === ctx.pagesConfigSourcePath || isPagePath(path, options)) {
199
+ await ctx.createOrUpdatePagesJSON();
137
200
  }
138
201
  });
139
202
  watcher.on("add", async (path) => {
140
203
  if (isPagePath(path, options)) {
141
- await createOrUpdatePagesJSON(options);
204
+ await ctx.createOrUpdatePagesJSON();
142
205
  }
143
206
  });
144
207
  watcher.on("unlink", async (path) => {
145
208
  if (isPagePath(path, options)) {
146
- await createOrUpdatePagesJSON(options);
209
+ await ctx.createOrUpdatePagesJSON();
147
210
  }
148
211
  });
212
+ },
213
+ resolveId(id) {
214
+ if (id === virtualModuleId) {
215
+ return resolvedVirtualModuleId;
216
+ }
217
+ },
218
+ load(id) {
219
+ if (id === resolvedVirtualModuleId) {
220
+ return ctx.virtualModule();
221
+ }
149
222
  }
150
223
  };
151
224
  };
152
-
153
- exports.VitePluginUniPages = VitePluginUniPages;
154
- exports.default = VitePluginUniPages;
155
- exports.defineMiddleware = defineMiddleware;
156
- exports.definePages = definePages;
225
+ var src_default = VitePluginUniPages;
226
+ // Annotate the CommonJS export names for ESM import in node:
227
+ 0 && (module.exports = {
228
+ VitePluginUniPages,
229
+ definePages
230
+ });
231
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/constant.ts","../src/context/index.ts","../src/config/index.ts"],"sourcesContent":["import { normalizePath, Plugin } from \"vite\";\nimport { ResolvedOptions, UserOptions } from \"./types\";\nimport { isPagePath } from \"./utils\";\nimport { virtualModuleId, resolvedVirtualModuleId } from \"./constant\";\nimport { Context } from \"./context\";\n\nexport * from \"./config\";\n\nfunction resolveOptions(userOptions: UserOptions): ResolvedOptions {\n return {\n pagesDir: \"src/pages\",\n outDir: \"src\",\n entry: \"pages.config\",\n extension: \"ts\",\n middlewaresDir: \"src/middlewares\",\n ...userOptions,\n };\n}\n\nexport const VitePluginUniPages = async (\n userOptions: UserOptions = {}\n): Promise<Plugin> => {\n const options = resolveOptions(userOptions);\n const ctx = new Context(options);\n\n return {\n name: \"vite-plugin-uni-pages\",\n enforce: \"pre\",\n configureServer({ watcher }) {\n watcher.add(ctx.pagesConfigSourcePath);\n watcher.on(\"change\", async (path) => {\n if (\n normalizePath(path) === ctx.pagesConfigSourcePath ||\n isPagePath(path, options)\n ) {\n await ctx.createOrUpdatePagesJSON();\n }\n });\n watcher.on(\"add\", async (path) => {\n if (isPagePath(path, options)) {\n await ctx.createOrUpdatePagesJSON();\n }\n });\n watcher.on(\"unlink\", async (path) => {\n if (isPagePath(path, options)) {\n await ctx.createOrUpdatePagesJSON();\n }\n });\n },\n resolveId(id) {\n if (id === virtualModuleId) {\n return resolvedVirtualModuleId;\n }\n },\n\n load(id) {\n if (id === resolvedVirtualModuleId) {\n return ctx.virtualModule();\n }\n },\n };\n};\n\nexport default VitePluginUniPages;\n","import { resolve } from \"path\";\nimport { ResolvedOptions } from \"./types\";\nimport { createFilter } from \"vite\";\nexport const isPagePath = (path: string, options: ResolvedOptions) => {\n const dirPath = resolve(process.cwd(), options.pagesDir);\n const filter = createFilter(dirPath + \"/**/*.(vue|nvue)\");\n return filter(path);\n // if (path.startsWith(dirPath)) return true;\n // return false;\n};\n","export const virtualModuleId = \"virtual:uni-pages\";\nexport const resolvedVirtualModuleId = \"\\0\" + virtualModuleId;\n","import { extname, join, relative, resolve } from \"path\";\nimport { loadConfig } from \"unconfig\";\nimport { normalizePath } from \"vite\";\nimport { PagesConfig } from \"../config/types\";\nimport { PageMeta, PagePathInfo, ResolvedOptions } from \"../types\";\nimport fg from \"fast-glob\";\nimport { parse as JSONParse } from \"jsonc-parser\";\nimport { parse } from \"@vue/compiler-dom\";\nimport fs from \"fs\";\nimport { defu } from \"defu\";\n\nexport class Context {\n options: ResolvedOptions;\n pagesConfig!: PagesConfig;\n pagesPathInfo: PagePathInfo[] = [];\n pagesMeta: PageMeta[] = [];\n constructor(options: ResolvedOptions) {\n this.options = options;\n this.createOrUpdatePagesJSON();\n }\n\n async loadUserPagesConfig() {\n const { config } = await loadConfig({\n sources: [\n {\n files: this.options.entry,\n extensions: [this.options.extension],\n },\n ],\n merge: false,\n });\n this.pagesConfig = config as PagesConfig;\n }\n\n async scanPages() {\n const files = await fg(\"**/*.(vue|nvue)\", {\n ignore: [\"node_modules\", \".git\", \"**/__*__/*\"],\n onlyFiles: true,\n cwd: resolve(process.cwd(), this.options.pagesDir),\n });\n const basePath = relative(\n resolve(process.cwd(), this.options.outDir),\n this.options.pagesDir\n );\n this.pagesPathInfo = files.map((file) => {\n return {\n relative: normalizePath(join(basePath, file)),\n absolute: normalizePath(\n resolve(process.cwd(), this.options.pagesDir, file)\n ),\n };\n });\n }\n\n async parsePage({ relative, absolute }: PagePathInfo): Promise<PageMeta> {\n const code = await fs.promises.readFile(absolute, {\n encoding: \"utf-8\",\n });\n const t = parse(code);\n const path = relative.replace(extname(relative), \"\");\n let pageMeta: PageMeta = {\n path,\n type: \"page\",\n };\n t?.children.forEach((v) => {\n if (v.type !== 1) {\n return;\n }\n if (v.tag === \"route\") {\n v.props.forEach((prop) => {\n if (prop.type === 6 && prop.name === \"type\") {\n pageMeta.type = prop.value?.content ?? pageMeta.type;\n }\n });\n const astContent = v.children?.[0];\n if (astContent && astContent.type === 2) {\n const _pageMeta = JSONParse(astContent.content);\n Object.keys(_pageMeta).forEach((key) => {\n pageMeta[key] = _pageMeta[key];\n });\n // overwrite path\n pageMeta[\"path\"] = path;\n }\n }\n });\n return pageMeta;\n }\n\n async mergePagesMeta() {\n const pagesMeta = await Promise.all(\n this.pagesPathInfo?.map(async (page) => await this.parsePage(page))\n );\n const pages = Object.values(defu({}, pagesMeta, this.pagesConfig.pages));\n // @ts-ignore\n pages.sort((a) => (a.type === \"home\" ? -1 : 0));\n // @ts-ignore\n this.pagesMeta = pages;\n }\n\n async createOrUpdatePagesJSON() {\n const outputName = \"pages.json\";\n const resolvedOutput = normalizePath(\n resolve(process.cwd(), this.options.outDir, outputName)\n );\n\n // 如果不存在,先输出一个占位文件\n if (!fs.existsSync(resolvedOutput)) {\n fs.writeFileSync(resolvedOutput, `{\"pages\": [{\"path\": \"\"}]}`, {\n encoding: \"utf-8\",\n });\n }\n\n await this.loadUserPagesConfig();\n await this.scanPages();\n await this.mergePagesMeta();\n\n fs.writeFileSync(\n resolvedOutput,\n JSON.stringify({\n ...this.pagesConfig,\n pages: this.pagesMeta,\n }),\n {\n encoding: \"utf-8\",\n }\n );\n }\n\n async virtualModule() {\n return `export const pages = ${JSON.stringify(this.pagesMeta)};`;\n }\n\n get pagesConfigSourcePath() {\n return normalizePath(\n resolve(process.cwd(), `${this.options.entry}.${this.options.extension}`)\n );\n }\n}\n","import { UserPagesConfig } from \"./types\";\nexport * from \"./types\";\nexport function definePages(config: UserPagesConfig) {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAsC;;;ACAtC,kBAAwB;AAExB,kBAA6B;AACtB,IAAM,aAAa,CAAC,MAAc,YAA6B;AACpE,QAAM,cAAU,qBAAQ,QAAQ,IAAI,GAAG,QAAQ,QAAQ;AACvD,QAAM,aAAS,0BAAa,UAAU,kBAAkB;AACxD,SAAO,OAAO,IAAI;AAGpB;;;ACTO,IAAM,kBAAkB;AACxB,IAAM,0BAA0B,OAAO;;;ACD9C,IAAAC,eAAiD;AACjD,sBAA2B;AAC3B,IAAAC,eAA8B;AAG9B,uBAAe;AACf,0BAAmC;AACnC,0BAAsB;AACtB,gBAAe;AACf,kBAAqB;AAEd,IAAM,UAAN,MAAc;AAAA,EAKnB,YAAY,SAA0B;AAFtC,yBAAgC,CAAC;AACjC,qBAAwB,CAAC;AAEvB,SAAK,UAAU;AACf,SAAK,wBAAwB;AAAA,EAC/B;AAAA,EAEA,MAAM,sBAAsB;AAC1B,UAAM,EAAE,OAAO,IAAI,UAAM,4BAAW;AAAA,MAClC,SAAS;AAAA,QACP;AAAA,UACE,OAAO,KAAK,QAAQ;AAAA,UACpB,YAAY,CAAC,KAAK,QAAQ,SAAS;AAAA,QACrC;AAAA,MACF;AAAA,MACA,OAAO;AAAA,IACT,CAAC;AACD,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,MAAM,YAAY;AAChB,UAAM,QAAQ,UAAM,iBAAAC,SAAG,mBAAmB;AAAA,MACxC,QAAQ,CAAC,gBAAgB,QAAQ,YAAY;AAAA,MAC7C,WAAW;AAAA,MACX,SAAK,sB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;AACT;;;AJIA,SAAS,eAAe,aAA2C;AACjE,SAAO;AAAA,IACL,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,WAAW;AAAA,IACX,gBAAgB;AAAA,IAChB,GAAG;AAAA,EACL;AACF;AAEO,IAAM,qBAAqB,OAChC,cAA2B,CAAC,MACR;AACpB,QAAM,UAAU,eAAe,WAAW;AAC1C,QAAM,MAAM,IAAI,QAAQ,OAAO;AAE/B,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,gBAAgB,EAAE,QAAQ,GAAG;AAC3B,cAAQ,IAAI,IAAI,qBAAqB;AACrC,cAAQ,GAAG,UAAU,OAAO,SAAS;AACnC,gBACE,4BAAc,IAAI,MAAM,IAAI,yBAC5B,WAAW,MAAM,OAAO,GACxB;AACA,gBAAM,IAAI,wBAAwB;AAAA,QACpC;AAAA,MACF,CAAC;AACD,cAAQ,GAAG,OAAO,OAAO,SAAS;AAChC,YAAI,WAAW,MAAM,OAAO,GAAG;AAC7B,gBAAM,IAAI,wBAAwB;AAAA,QACpC;AAAA,MACF,CAAC;AACD,cAAQ,GAAG,UAAU,OAAO,SAAS;AACnC,YAAI,WAAW,MAAM,OAAO,GAAG;AAC7B,gBAAM,IAAI,wBAAwB;AAAA,QACpC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA,UAAU,IAAI;AACZ,UAAI,OAAO,iBAAiB;AAC1B,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IAEA,KAAK,IAAI;AACP,UAAI,OAAO,yBAAyB;AAClC,eAAO,IAAI,cAAc;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,cAAQ;","names":["import_vite","import_path","import_vite","fg","relative","fs","_a","JSONParse"]}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Plugin } from 'vite';
2
+ export { PagesConfig, UserPagesConfig, definePages } from './config/index.js';
2
3
 
3
4
  interface Options {
4
5
  /**
@@ -21,33 +22,15 @@ interface Options {
21
22
  * @default "ts"
22
23
  */
23
24
  extension: string;
25
+ /**
26
+ * middlewares dir
27
+ * @default "src/middlewares"
28
+ */
29
+ middlewaresDir: string;
24
30
  }
25
31
  interface UserOptions extends Partial<Options> {
26
32
  }
27
33
 
28
- interface PagesConfig {
29
- pages: any;
30
- globalStyle: any;
31
- easycom: any;
32
- tabBar: any;
33
- condition: any;
34
- subPackages: any;
35
- preloadRule: any;
36
- workers: any;
37
- leftWindow: any;
38
- topWindow: any;
39
- rightWindow: any;
40
- uniIdRouter: any;
41
- }
42
- interface UserPagesConfig extends Partial<PagesConfig> {
43
- }
44
-
45
- declare function definePages(config: UserPagesConfig): UserPagesConfig;
46
-
47
- declare type Middleware = (to: string, from: string) => void | boolean | string;
48
-
49
- declare function defineMiddleware(middleware: Middleware): Middleware;
50
-
51
34
  declare const VitePluginUniPages: (userOptions?: UserOptions) => Promise<Plugin>;
52
35
 
53
- export { Middleware, PagesConfig, UserPagesConfig, VitePluginUniPages, VitePluginUniPages as default, defineMiddleware, definePages };
36
+ export { VitePluginUniPages, VitePluginUniPages as default };
package/dist/index.js ADDED
@@ -0,0 +1,199 @@
1
+ // src/index.ts
2
+ import { normalizePath as normalizePath2 } from "vite";
3
+
4
+ // src/utils.ts
5
+ import { resolve } from "path";
6
+ import { createFilter } from "vite";
7
+ var isPagePath = (path, options) => {
8
+ const dirPath = resolve(process.cwd(), options.pagesDir);
9
+ const filter = createFilter(dirPath + "/**/*.(vue|nvue)");
10
+ return filter(path);
11
+ };
12
+
13
+ // src/constant.ts
14
+ var virtualModuleId = "virtual:uni-pages";
15
+ var resolvedVirtualModuleId = "\0" + virtualModuleId;
16
+
17
+ // src/context/index.ts
18
+ import { extname, join, relative, resolve as resolve2 } from "path";
19
+ import { loadConfig } from "unconfig";
20
+ import { normalizePath } from "vite";
21
+ import fg from "fast-glob";
22
+ import { parse as JSONParse } from "jsonc-parser";
23
+ import { parse } from "@vue/compiler-dom";
24
+ import fs from "fs";
25
+ import { defu } from "defu";
26
+ var Context = class {
27
+ constructor(options) {
28
+ this.pagesPathInfo = [];
29
+ this.pagesMeta = [];
30
+ this.options = options;
31
+ this.createOrUpdatePagesJSON();
32
+ }
33
+ async loadUserPagesConfig() {
34
+ const { config } = await loadConfig({
35
+ sources: [
36
+ {
37
+ files: this.options.entry,
38
+ extensions: [this.options.extension]
39
+ }
40
+ ],
41
+ merge: false
42
+ });
43
+ this.pagesConfig = config;
44
+ }
45
+ async scanPages() {
46
+ const files = await fg("**/*.(vue|nvue)", {
47
+ ignore: ["node_modules", ".git", "**/__*__/*"],
48
+ onlyFiles: true,
49
+ cwd: resolve2(process.cwd(), this.options.pagesDir)
50
+ });
51
+ const basePath = relative(
52
+ resolve2(process.cwd(), this.options.outDir),
53
+ this.options.pagesDir
54
+ );
55
+ this.pagesPathInfo = files.map((file) => {
56
+ return {
57
+ relative: normalizePath(join(basePath, file)),
58
+ absolute: normalizePath(
59
+ resolve2(process.cwd(), this.options.pagesDir, file)
60
+ )
61
+ };
62
+ });
63
+ }
64
+ async parsePage({ relative: relative2, absolute }) {
65
+ const code = await fs.promises.readFile(absolute, {
66
+ encoding: "utf-8"
67
+ });
68
+ const t = parse(code);
69
+ const path = relative2.replace(extname(relative2), "");
70
+ let pageMeta = {
71
+ path,
72
+ type: "page"
73
+ };
74
+ t == null ? void 0 : t.children.forEach((v) => {
75
+ var _a;
76
+ if (v.type !== 1) {
77
+ return;
78
+ }
79
+ if (v.tag === "route") {
80
+ v.props.forEach((prop) => {
81
+ var _a2;
82
+ if (prop.type === 6 && prop.name === "type") {
83
+ pageMeta.type = ((_a2 = prop.value) == null ? void 0 : _a2.content) ?? pageMeta.type;
84
+ }
85
+ });
86
+ const astContent = (_a = v.children) == null ? void 0 : _a[0];
87
+ if (astContent && astContent.type === 2) {
88
+ const _pageMeta = JSONParse(astContent.content);
89
+ Object.keys(_pageMeta).forEach((key) => {
90
+ pageMeta[key] = _pageMeta[key];
91
+ });
92
+ pageMeta["path"] = path;
93
+ }
94
+ }
95
+ });
96
+ return pageMeta;
97
+ }
98
+ async mergePagesMeta() {
99
+ var _a;
100
+ const pagesMeta = await Promise.all(
101
+ (_a = this.pagesPathInfo) == null ? void 0 : _a.map(async (page) => await this.parsePage(page))
102
+ );
103
+ const pages = Object.values(defu({}, pagesMeta, this.pagesConfig.pages));
104
+ pages.sort((a) => a.type === "home" ? -1 : 0);
105
+ this.pagesMeta = pages;
106
+ }
107
+ async createOrUpdatePagesJSON() {
108
+ const outputName = "pages.json";
109
+ const resolvedOutput = normalizePath(
110
+ resolve2(process.cwd(), this.options.outDir, outputName)
111
+ );
112
+ if (!fs.existsSync(resolvedOutput)) {
113
+ fs.writeFileSync(resolvedOutput, `{"pages": [{"path": ""}]}`, {
114
+ encoding: "utf-8"
115
+ });
116
+ }
117
+ await this.loadUserPagesConfig();
118
+ await this.scanPages();
119
+ await this.mergePagesMeta();
120
+ fs.writeFileSync(
121
+ resolvedOutput,
122
+ JSON.stringify({
123
+ ...this.pagesConfig,
124
+ pages: this.pagesMeta
125
+ }),
126
+ {
127
+ encoding: "utf-8"
128
+ }
129
+ );
130
+ }
131
+ async virtualModule() {
132
+ return `export const pages = ${JSON.stringify(this.pagesMeta)};`;
133
+ }
134
+ get pagesConfigSourcePath() {
135
+ return normalizePath(
136
+ resolve2(process.cwd(), `${this.options.entry}.${this.options.extension}`)
137
+ );
138
+ }
139
+ };
140
+
141
+ // src/config/index.ts
142
+ function definePages(config) {
143
+ return config;
144
+ }
145
+
146
+ // src/index.ts
147
+ function resolveOptions(userOptions) {
148
+ return {
149
+ pagesDir: "src/pages",
150
+ outDir: "src",
151
+ entry: "pages.config",
152
+ extension: "ts",
153
+ middlewaresDir: "src/middlewares",
154
+ ...userOptions
155
+ };
156
+ }
157
+ var VitePluginUniPages = async (userOptions = {}) => {
158
+ const options = resolveOptions(userOptions);
159
+ const ctx = new Context(options);
160
+ return {
161
+ name: "vite-plugin-uni-pages",
162
+ enforce: "pre",
163
+ configureServer({ watcher }) {
164
+ watcher.add(ctx.pagesConfigSourcePath);
165
+ watcher.on("change", async (path) => {
166
+ if (normalizePath2(path) === ctx.pagesConfigSourcePath || isPagePath(path, options)) {
167
+ await ctx.createOrUpdatePagesJSON();
168
+ }
169
+ });
170
+ watcher.on("add", async (path) => {
171
+ if (isPagePath(path, options)) {
172
+ await ctx.createOrUpdatePagesJSON();
173
+ }
174
+ });
175
+ watcher.on("unlink", async (path) => {
176
+ if (isPagePath(path, options)) {
177
+ await ctx.createOrUpdatePagesJSON();
178
+ }
179
+ });
180
+ },
181
+ resolveId(id) {
182
+ if (id === virtualModuleId) {
183
+ return resolvedVirtualModuleId;
184
+ }
185
+ },
186
+ load(id) {
187
+ if (id === resolvedVirtualModuleId) {
188
+ return ctx.virtualModule();
189
+ }
190
+ }
191
+ };
192
+ };
193
+ var src_default = VitePluginUniPages;
194
+ export {
195
+ VitePluginUniPages,
196
+ src_default as default,
197
+ definePages
198
+ };
199
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/constant.ts","../src/context/index.ts","../src/config/index.ts"],"sourcesContent":["import { normalizePath, Plugin } from \"vite\";\nimport { ResolvedOptions, UserOptions } from \"./types\";\nimport { isPagePath } from \"./utils\";\nimport { virtualModuleId, resolvedVirtualModuleId } from \"./constant\";\nimport { Context } from \"./context\";\n\nexport * from \"./config\";\n\nfunction resolveOptions(userOptions: UserOptions): ResolvedOptions {\n return {\n pagesDir: \"src/pages\",\n outDir: \"src\",\n entry: \"pages.config\",\n extension: \"ts\",\n middlewaresDir: \"src/middlewares\",\n ...userOptions,\n };\n}\n\nexport const VitePluginUniPages = async (\n userOptions: UserOptions = {}\n): Promise<Plugin> => {\n const options = resolveOptions(userOptions);\n const ctx = new Context(options);\n\n return {\n name: \"vite-plugin-uni-pages\",\n enforce: \"pre\",\n configureServer({ watcher }) {\n watcher.add(ctx.pagesConfigSourcePath);\n watcher.on(\"change\", async (path) => {\n if (\n normalizePath(path) === ctx.pagesConfigSourcePath ||\n isPagePath(path, options)\n ) {\n await ctx.createOrUpdatePagesJSON();\n }\n });\n watcher.on(\"add\", async (path) => {\n if (isPagePath(path, options)) {\n await ctx.createOrUpdatePagesJSON();\n }\n });\n watcher.on(\"unlink\", async (path) => {\n if (isPagePath(path, options)) {\n await ctx.createOrUpdatePagesJSON();\n }\n });\n },\n resolveId(id) {\n if (id === virtualModuleId) {\n return resolvedVirtualModuleId;\n }\n },\n\n load(id) {\n if (id === resolvedVirtualModuleId) {\n return ctx.virtualModule();\n }\n },\n };\n};\n\nexport default VitePluginUniPages;\n","import { resolve } from \"path\";\nimport { ResolvedOptions } from \"./types\";\nimport { createFilter } from \"vite\";\nexport const isPagePath = (path: string, options: ResolvedOptions) => {\n const dirPath = resolve(process.cwd(), options.pagesDir);\n const filter = createFilter(dirPath + \"/**/*.(vue|nvue)\");\n return filter(path);\n // if (path.startsWith(dirPath)) return true;\n // return false;\n};\n","export const virtualModuleId = \"virtual:uni-pages\";\nexport const resolvedVirtualModuleId = \"\\0\" + virtualModuleId;\n","import { extname, join, relative, resolve } from \"path\";\nimport { loadConfig } from \"unconfig\";\nimport { normalizePath } from \"vite\";\nimport { PagesConfig } from \"../config/types\";\nimport { PageMeta, PagePathInfo, ResolvedOptions } from \"../types\";\nimport fg from \"fast-glob\";\nimport { parse as JSONParse } from \"jsonc-parser\";\nimport { parse } from \"@vue/compiler-dom\";\nimport fs from \"fs\";\nimport { defu } from \"defu\";\n\nexport class Context {\n options: ResolvedOptions;\n pagesConfig!: PagesConfig;\n pagesPathInfo: PagePathInfo[] = [];\n pagesMeta: PageMeta[] = [];\n constructor(options: ResolvedOptions) {\n this.options = options;\n this.createOrUpdatePagesJSON();\n }\n\n async loadUserPagesConfig() {\n const { config } = await loadConfig({\n sources: [\n {\n files: this.options.entry,\n extensions: [this.options.extension],\n },\n ],\n merge: false,\n });\n this.pagesConfig = config as PagesConfig;\n }\n\n async scanPages() {\n const files = await fg(\"**/*.(vue|nvue)\", {\n ignore: [\"node_modules\", \".git\", \"**/__*__/*\"],\n onlyFiles: true,\n cwd: resolve(process.cwd(), this.options.pagesDir),\n });\n const basePath = relative(\n resolve(process.cwd(), this.options.outDir),\n this.options.pagesDir\n );\n this.pagesPathInfo = files.map((file) => {\n return {\n relative: normalizePath(join(basePath, file)),\n absolute: normalizePath(\n resolve(process.cwd(), this.options.pagesDir, file)\n ),\n };\n });\n }\n\n async parsePage({ relative, absolute }: PagePathInfo): Promise<PageMeta> {\n const code = await fs.promises.readFile(absolute, {\n encoding: \"utf-8\",\n });\n const t = parse(code);\n const path = relative.replace(extname(relative), \"\");\n let pageMeta: PageMeta = {\n path,\n type: \"page\",\n };\n t?.children.forEach((v) => {\n if (v.type !== 1) {\n return;\n }\n if (v.tag === \"route\") {\n v.props.forEach((prop) => {\n if (prop.type === 6 && prop.name === \"type\") {\n pageMeta.type = prop.value?.content ?? pageMeta.type;\n }\n });\n const astContent = v.children?.[0];\n if (astContent && astContent.type === 2) {\n const _pageMeta = JSONParse(astContent.content);\n Object.keys(_pageMeta).forEach((key) => {\n pageMeta[key] = _pageMeta[key];\n });\n // overwrite path\n pageMeta[\"path\"] = path;\n }\n }\n });\n return pageMeta;\n }\n\n async mergePagesMeta() {\n const pagesMeta = await Promise.all(\n this.pagesPathInfo?.map(async (page) => await this.parsePage(page))\n );\n const pages = Object.values(defu({}, pagesMeta, this.pagesConfig.pages));\n // @ts-ignore\n pages.sort((a) => (a.type === \"home\" ? -1 : 0));\n // @ts-ignore\n this.pagesMeta = pages;\n }\n\n async createOrUpdatePagesJSON() {\n const outputName = \"pages.json\";\n const resolvedOutput = normalizePath(\n resolve(process.cwd(), this.options.outDir, outputName)\n );\n\n // 如果不存在,先输出一个占位文件\n if (!fs.existsSync(resolvedOutput)) {\n fs.writeFileSync(resolvedOutput, `{\"pages\": [{\"path\": \"\"}]}`, {\n encoding: \"utf-8\",\n });\n }\n\n await this.loadUserPagesConfig();\n await this.scanPages();\n await this.mergePagesMeta();\n\n fs.writeFileSync(\n resolvedOutput,\n JSON.stringify({\n ...this.pagesConfig,\n pages: this.pagesMeta,\n }),\n {\n encoding: \"utf-8\",\n }\n );\n }\n\n async virtualModule() {\n return `export const pages = ${JSON.stringify(this.pagesMeta)};`;\n }\n\n get pagesConfigSourcePath() {\n return normalizePath(\n resolve(process.cwd(), `${this.options.entry}.${this.options.extension}`)\n );\n }\n}\n","import { UserPagesConfig } from \"./types\";\nexport * from \"./types\";\nexport function definePages(config: UserPagesConfig) {\n return config;\n}\n"],"mappings":";AAAA,SAAS,iBAAAA,sBAA6B;;;ACAtC,SAAS,eAAe;AAExB,SAAS,oBAAoB;AACtB,IAAM,aAAa,CAAC,MAAc,YAA6B;AACpE,QAAM,UAAU,QAAQ,QAAQ,IAAI,GAAG,QAAQ,QAAQ;AACvD,QAAM,SAAS,aAAa,UAAU,kBAAkB;AACxD,SAAO,OAAO,IAAI;AAGpB;;;ACTO,IAAM,kBAAkB;AACxB,IAAM,0BAA0B,OAAO;;;ACD9C,SAAS,SAAS,MAAM,UAAU,WAAAC,gBAAe;AACjD,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAG9B,OAAO,QAAQ;AACf,SAAS,SAAS,iBAAiB;AACnC,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,SAAS,YAAY;AAEd,IAAM,UAAN,MAAc;AAAA,EAKnB,YAAY,SAA0B;AAFtC,yBAAgC,CAAC;AACjC,qBAAwB,CAAC;AAEvB,SAAK,UAAU;AACf,SAAK,wBAAwB;AAAA,EAC/B;AAAA,EAEA,MAAM,sBAAsB;AAC1B,UAAM,EAAE,OAAO,IAAI,MAAM,WAAW;AAAA,MAClC,SAAS;AAAA,QACP;AAAA,UACE,OAAO,KAAK,QAAQ;AAAA,UACpB,YAAY,CAAC,KAAK,QAAQ,SAAS;AAAA,QACrC;AAAA,MACF;AAAA,MACA,OAAO;AAAA,IACT,CAAC;AACD,SAAK,c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 @@
1
1
  {
2
2
  "name": "@uni-helper/vite-plugin-uni-pages",
3
3
  "type": "module",
4
- "version": "0.0.1",
4
+ "version": "0.0.2",
5
5
  "packageManager": "pnpm@7.14.0",
6
6
  "description": "File system based routing for uni-app applications using Vite",
7
7
  "author": "KeJun",
@@ -18,40 +18,38 @@
18
18
  ".": {
19
19
  "types": "./dist/index.d.ts",
20
20
  "require": "./dist/index.cjs",
21
- "import": "./dist/index.mjs"
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./config": {
24
+ "types": "./dist/config/index.d.ts",
25
+ "require": "./dist/config/index.cjs",
26
+ "import": "./dist/config/index.js"
27
+ },
28
+ "./client": {
29
+ "types": "./client.d.ts"
22
30
  }
23
31
  },
24
32
  "main": "./dist/index.mjs",
25
- "module": "./dist/index.mjs",
33
+ "module": "./dist/index.js",
26
34
  "types": "./dist/index.d.ts",
27
- "typesVersions": {
28
- "*": {
29
- "*": [
30
- "./dist/*",
31
- "./dist/index.d.ts"
32
- ]
33
- }
34
- },
35
35
  "files": [
36
- "dist"
36
+ "dist",
37
+ "client.d.ts"
37
38
  ],
38
39
  "scripts": {
39
- "build": "unbuild",
40
- "dev": "unbuild --stub",
40
+ "build": "tsup",
41
+ "dev": "tsup --watch",
41
42
  "play": "nr -C playground dev:h5",
42
43
  "prepublishOnly": "pnpm build",
43
44
  "release": "bumpp && npm publish --access public",
44
- "start": "esno src/index.ts",
45
45
  "test": "vitest"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/node": "^18.11.9",
49
49
  "bumpp": "^8.2.1",
50
- "esno": "^0.16.3",
50
+ "tsup": "^6.5.0",
51
51
  "typescript": "^4.8.4",
52
- "unbuild": "^0.9.4",
53
- "vite": "^3.2.3",
54
- "vitest": "^0.24.5"
52
+ "vite": "^3.2.3"
55
53
  },
56
54
  "dependencies": {
57
55
  "@vue/compiler-dom": "^3.2.45",
package/dist/index.mjs DELETED
@@ -1,149 +0,0 @@
1
- import { createFilter, normalizePath } from 'vite';
2
- import { loadConfig } from 'unconfig';
3
- import { resolve, relative, join, extname } from 'path';
4
- import fs from 'fs';
5
- import fg from 'fast-glob';
6
- import { parse } from '@vue/compiler-dom';
7
- import { parse as parse$1 } from 'jsonc-parser';
8
- import { defu } from 'defu';
9
-
10
- const isPagePath = (path, options) => {
11
- const dirPath = resolve(process.cwd(), options.pagesDir);
12
- const filter = createFilter(dirPath + "/**/*.(vue|nvue)");
13
- return filter(path);
14
- };
15
-
16
- function definePages(config) {
17
- return config;
18
- }
19
-
20
- function defineMiddleware(middleware) {
21
- return middleware;
22
- }
23
-
24
- function resolveOptions(userOptions) {
25
- return {
26
- pagesDir: "src/pages",
27
- outDir: "src",
28
- entry: "pages.config",
29
- extension: "ts",
30
- ...userOptions
31
- };
32
- }
33
- const loadUserPagesConfig = async (options) => {
34
- const { config } = await loadConfig({
35
- sources: [
36
- {
37
- files: options.entry,
38
- extensions: [options.extension]
39
- }
40
- ],
41
- merge: false
42
- });
43
- return config;
44
- };
45
- const scanPages = async (options) => {
46
- const files = await fg("**/*.(vue|nvue)", {
47
- ignore: ["node_modules", ".git", "**/__*__/*"],
48
- onlyFiles: true,
49
- cwd: resolve(process.cwd(), options.pagesDir)
50
- });
51
- const basePath = relative(
52
- resolve(process.cwd(), options.outDir),
53
- options.pagesDir
54
- );
55
- return files.map((file) => {
56
- return {
57
- relative: normalizePath(join(basePath, file)),
58
- absolute: normalizePath(resolve(process.cwd(), options.pagesDir, file))
59
- };
60
- });
61
- };
62
- const parsePage = async ({
63
- relative: relative2,
64
- absolute
65
- }) => {
66
- const code = await fs.promises.readFile(absolute, {
67
- encoding: "utf-8"
68
- });
69
- const t = parse(code);
70
- const path = relative2.replace(extname(relative2), "");
71
- let pageMeta = {
72
- path,
73
- type: "page"
74
- };
75
- t?.children.forEach((v) => {
76
- if (v.type !== 1) {
77
- return;
78
- }
79
- if (v.tag === "route") {
80
- v.props.forEach((prop) => {
81
- if (prop.type === 6 && prop.name === "type") {
82
- pageMeta.type = prop.value?.content ?? pageMeta.type;
83
- }
84
- });
85
- const astContent = v.children?.[0];
86
- if (astContent && astContent.type === 2) {
87
- const _pageMeta = parse$1(astContent.content);
88
- Object.keys(_pageMeta).forEach((key) => {
89
- pageMeta[key] = _pageMeta[key];
90
- });
91
- pageMeta["path"] = path;
92
- }
93
- }
94
- });
95
- return pageMeta;
96
- };
97
- const createOrUpdatePagesJSON = async (options, path) => {
98
- const outputName = "pages.json";
99
- const resolvedOutput = normalizePath(
100
- resolve(process.cwd(), options.outDir, outputName)
101
- );
102
- if (!fs.existsSync(resolvedOutput)) {
103
- fs.writeFileSync(resolvedOutput, "{}", {
104
- encoding: "utf-8"
105
- });
106
- }
107
- const config = await loadUserPagesConfig(options);
108
- const pagesPathList = await scanPages(options);
109
- const pagesMeta = await Promise.all(
110
- pagesPathList.map(async (page) => await parsePage(page))
111
- );
112
- const pages = Object.values(defu({}, pagesMeta, config.pages));
113
- pages.sort((a) => a.type === "home" ? -1 : 0);
114
- config.pages = pages;
115
- fs.writeFileSync(resolvedOutput, JSON.stringify(config), {
116
- encoding: "utf-8"
117
- });
118
- };
119
- const VitePluginUniPages = async (userOptions = {}) => {
120
- const options = resolveOptions(userOptions);
121
- const pagesConfigSource = normalizePath(
122
- resolve(process.cwd(), `${options.entry}.${options.extension}`)
123
- );
124
- await createOrUpdatePagesJSON(options);
125
- return {
126
- name: "vite-plugin-uni-pages",
127
- enforce: "pre",
128
- configureServer({ watcher }) {
129
- watcher.add(pagesConfigSource);
130
- watcher.on("change", async (path) => {
131
- if (normalizePath(path) === pagesConfigSource || isPagePath(path, options)) {
132
- await createOrUpdatePagesJSON(options);
133
- }
134
- });
135
- watcher.on("add", async (path) => {
136
- if (isPagePath(path, options)) {
137
- await createOrUpdatePagesJSON(options);
138
- }
139
- });
140
- watcher.on("unlink", async (path) => {
141
- if (isPagePath(path, options)) {
142
- await createOrUpdatePagesJSON(options);
143
- }
144
- });
145
- }
146
- };
147
- };
148
-
149
- export { VitePluginUniPages, VitePluginUniPages as default, defineMiddleware, definePages };