vite-plugin-generoutes 1.0.1 → 1.1.0-beta.3

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Ronnie Zhang(大脸怪)
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Ronnie Zhang(大脸怪)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -45,12 +45,20 @@ export default defineConfig({
45
45
 
46
46
  ### ⚙️ Configuration Options
47
47
 
48
- | Option | Type | Default | Description |
49
- | --------------- | ---------- | ------------------------ | ------------------------------------------------------- |
50
- | `pagesFolder` | `string` | `'src/pages'` | Path to pages folder |
51
- | `ignoreFolders` | `string[]` | `['components']` | Folders to ignore when generating routes |
52
- | `routesPath` | `string` | `'src/router/routes.js'` | Path to generated routes file, can also be a `.ts` file |
53
- | `nested` | `boolean` | `false` | Whether to generate nested routes |
48
+ | Option | Type | Default | Description |
49
+ | --------------- | ---------- | ---------------- | ----------------------------------------------------------------------------------------------------------------- |
50
+ | `pagesFolder` | `string` | `'src/pages'` | Path to pages folder |
51
+ | `ignoreFolders` | `string[]` | `['components']` | Folders to ignore when generating routes |
52
+ | `routesPath` | `string` | Auto-detected | Path to generated routes file. Auto-detected based on `tsconfig.json` presence (`.ts` if exists, otherwise `.js`) |
53
+ | `nested` | `boolean` | `false` | Whether to generate nested routes |
54
+
55
+ ### 📘 TypeScript Support
56
+
57
+ This plugin has first-class TypeScript support:
58
+
59
+ - **Auto-detection**: Automatically detects TypeScript projects by checking for `tsconfig.json`
60
+ - **Type definitions**: When generating routes for TypeScript projects, the plugin automatically includes type definitions for `RouteMeta` and `GeneratedRoute`
61
+ - **Route typing**: Generated routes are properly typed with `RouteRecordRaw` from `vue-router`
54
62
 
55
63
  ### 📝 Routing Conventions
56
64
 
@@ -127,4 +135,20 @@ export default defineConfig({
127
135
  })
128
136
  ```
129
137
 
138
+ ### 💡 Troubleshooting
139
+
140
+ **Issue**: Route path shows error: *Cannot find module "/src/pages/xxx.vue" or its corresponding type declarations.* Unable to navigate to the file with F12.
141
+
142
+ **Solution**: Add the following configuration to the `compilerOptions` in your `jsconfig.json` or `tsconfig.json`:
143
+ ```json
144
+ {
145
+ "compilerOptions": {
146
+ "baseUrl": ".",
147
+ "paths": {
148
+ "/src/*": ["src/*"]
149
+ }
150
+ }
151
+ }
152
+ ```
153
+
130
154
  [中文文档](./README.zh_CN.md)
package/README.zh_CN.md CHANGED
@@ -45,12 +45,20 @@ export default defineConfig({
45
45
 
46
46
  ### ⚙️ 配置选项
47
47
 
48
- | 选项 | 类型 | 默认值 | 描述 |
49
- | --------------- | ---------- | ------------------------ | ------------------------------------- |
50
- | `pagesFolder` | `string` | `'src/pages'` | 页面文件夹路径 |
51
- | `ignoreFolders` | `string[]` | `['components']` | 生成路由时忽略的文件夹 |
52
- | `routesPath` | `string` | `'src/router/routes.js'` | 生成的路由文件路径,也可以是`.ts`文件 |
53
- | `nested` | `boolean` | `false` | 是否生成嵌套路由 |
48
+ | 选项 | 类型 | 默认值 | 描述 |
49
+ | --------------- | ---------- | ---------------- | ----------------------------------------------------------------------------------------- |
50
+ | `pagesFolder` | `string` | `'src/pages'` | 页面文件夹路径 |
51
+ | `ignoreFolders` | `string[]` | `['components']` | 生成路由时忽略的文件夹 |
52
+ | `routesPath` | `string` | 自动检测 | 生成的路由文件路径,根据 `tsconfig.json` 是否存在自动检测(存在则为 `.ts`,否则为 `.js`) |
53
+ | `nested` | `boolean` | `false` | 是否生成嵌套路由 |
54
+
55
+ ### 📘 TypeScript 支持
56
+
57
+ 本插件对 TypeScript 提供一流支持:
58
+
59
+ - **自动检测**:通过检查 `tsconfig.json` 自动检测 TypeScript 项目
60
+ - **类型定义**:为 TypeScript 项目生成路由时,插件会自动包含 `RouteMeta` 和 `GeneratedRoute` 的类型定义
61
+ - **路由类型**:生成的路由使用 `vue-router` 的 `RouteRecordRaw` 进行正确的类型标注
54
62
 
55
63
  ### 📝 路由规则
56
64
 
@@ -123,8 +131,24 @@ export default defineConfig({
123
131
  routesPath: 'src/router/routes.js',
124
132
  nested: true
125
133
  })
126
- ]
134
+ ],
127
135
  })
128
136
  ```
129
137
 
138
+ ### 💡 常见问题
139
+
140
+ 1、路由的path报红:*找不到模块“/src/pages/xxx.vue”或其相应的类型声明。*,按F12无法跳转至对应的文件
141
+
142
+ 解决方法:在 jsconfig.json 或者 tsconfig.json 的 compilerOptions中添加如下配置
143
+ ```json
144
+ {
145
+ "compilerOptions": {
146
+ "baseUrl": ".",
147
+ "paths": {
148
+ "/src/*": ["src/*"]
149
+ }
150
+ }
151
+ }
152
+ ```
153
+
130
154
  [English Documentation](./README.md)
package/dist/index.d.ts CHANGED
@@ -1,5 +1,40 @@
1
1
  import { Plugin } from 'vite';
2
2
 
3
+ /**
4
+ * Route meta information
5
+ */
6
+ interface RouteMeta {
7
+ /** Route title */
8
+ title?: string;
9
+ /** Route icon */
10
+ icon?: string;
11
+ /** Whether authentication is required */
12
+ requiresAuth?: boolean;
13
+ /** Whether the route is enabled */
14
+ enabled?: boolean;
15
+ /** Custom properties */
16
+ [key: string]: unknown;
17
+ }
18
+ /**
19
+ * Internal route representation used during generation
20
+ */
21
+ interface InternalRoute {
22
+ /** Route name */
23
+ name: string;
24
+ /** Route path */
25
+ path: string;
26
+ /** Redirect path */
27
+ redirect?: string;
28
+ /** Route component placeholder */
29
+ component?: string;
30
+ /** Route meta information */
31
+ meta: RouteMeta;
32
+ /** Parent route name (for nested routes) */
33
+ parent?: string;
34
+ /** Child routes */
35
+ children?: InternalRoute[];
36
+ }
37
+
3
38
  /**********************************
4
39
  * @Author: Ronnie Zhang
5
40
  * @LastEditor: Ronnie Zhang
@@ -8,6 +43,25 @@ import { Plugin } from 'vite';
8
43
  * Copyright © 2023 Ronnie Zhang(大脸怪) | https://isme.top
9
44
  **********************************/
10
45
 
46
+ /**
47
+ * Generated route record with proper typing for vue-router
48
+ */
49
+ interface GeneratedRoute {
50
+ /** Route name */
51
+ name: string;
52
+ /** Route path */
53
+ path: string;
54
+ /** Redirect path */
55
+ redirect?: string;
56
+ /** Route component */
57
+ component?: () => Promise<any>;
58
+ /** Route meta information */
59
+ meta: RouteMeta;
60
+ /** Parent route name (for nested routes) */
61
+ parent?: string;
62
+ /** Child routes */
63
+ children?: GeneratedRoute[];
64
+ }
11
65
  interface Options {
12
66
  /**
13
67
  * pages folder
@@ -23,8 +77,9 @@ interface Options {
23
77
  ignoreFolders: string[];
24
78
  /**
25
79
  * routes file path, It can also be a ts file,such as `src/router/routes.ts`
80
+ * Auto-detected based on tsconfig.json presence if not specified
26
81
  *
27
- * @default src/router/routes.js
82
+ * @default src/router/routes.ts (if tsconfig.json exists) or src/router/routes.js
28
83
  */
29
84
  routesPath: string;
30
85
  /**
@@ -36,4 +91,4 @@ interface Options {
36
91
  }
37
92
  declare function VitePluginGeneroutes(options?: Partial<Options>): Plugin;
38
93
 
39
- export { VitePluginGeneroutes as default };
94
+ export { type GeneratedRoute, type InternalRoute, type Options, type RouteMeta, VitePluginGeneroutes, VitePluginGeneroutes as default };
package/dist/index.js CHANGED
@@ -61,13 +61,18 @@ function findDuplicateRoutes(routes) {
61
61
  // src/index.ts
62
62
  function VitePluginGeneroutes(options = {}) {
63
63
  if (options.routesPath && ![".ts", ".js"].includes(path.extname(options.routesPath)))
64
- throw new Error("routesPath must be a js or ts file path, such as src/router/generoutes.js");
64
+ throw new Error("routesPath must be a js or ts file path, such as src/router/routes.js");
65
65
  let rootDir;
66
+ let routesPath;
67
+ let isTypeScript;
66
68
  const pagesFolder = options.pagesFolder || "src/pages";
67
- const routesPath = options.routesPath || "src/router/routes.js";
68
69
  const ignoreFolders = options.ignoreFolders || ["components"];
69
70
  const nested = options.nested || false;
70
71
  const defineOptionsCache = /* @__PURE__ */ new Map();
72
+ function detectTypeScriptProject() {
73
+ const tsconfigPath = path.resolve(rootDir, "tsconfig.json");
74
+ return fs.existsSync(tsconfigPath);
75
+ }
71
76
  function generateMenusAndRoutes() {
72
77
  const pages = globSync(`${pagesFolder}/**/*.vue`, { ignore: ignoreFolders.map((folder) => `${pagesFolder}/**/${folder}/**`) });
73
78
  const routes = pages.map((filePath) => {
@@ -89,7 +94,7 @@ function VitePluginGeneroutes(options = {}) {
89
94
  meta,
90
95
  parent: defineOptions.parent
91
96
  };
92
- }).filter(Boolean);
97
+ }).filter((route) => route !== null);
93
98
  const { duplicateNames, duplicatePaths } = findDuplicateRoutes(routes);
94
99
  if (duplicateNames.length)
95
100
  console.warn(`Warning: Duplicate names found in routes: ${duplicateNames.join(", ")}`);
@@ -101,13 +106,48 @@ function VitePluginGeneroutes(options = {}) {
101
106
  }
102
107
  async function writerRoutesFile(isInit = false) {
103
108
  const { routes } = generateMenusAndRoutes();
109
+ const typeDefinitions = isTypeScript ? `
110
+ import type { RouteRecordRaw } from 'vue-router'
111
+
112
+ /**
113
+ * Route meta information
114
+ */
115
+ export interface RouteMeta {
116
+ /** Page title */
117
+ title?: string
118
+ /** Page icon */
119
+ icon?: string
120
+ /** Page code */
121
+ code?: string
122
+ /** Whether authentication is required */
123
+ requireAuth?: boolean
124
+ /** Whether to keep alive */
125
+ keepAlive?: boolean
126
+ /** Whether it's the home page */
127
+ isHome?: boolean
128
+ /** Whether it's a login page */
129
+ isLogin?: boolean
130
+ /** Custom properties */
131
+ [key: string]: unknown
132
+ }
133
+
134
+ /**
135
+ * Generated route type with proper typing
136
+ */
137
+ export type GeneratedRoute = RouteRecordRaw & {
138
+ meta?: RouteMeta
139
+ children?: GeneratedRoute[]
140
+ }
141
+ ` : "";
142
+ const routesType = isTypeScript ? ": GeneratedRoute[]" : "";
104
143
  let routesStr = `
105
144
  // Generated by vite-plugin-generoutes, don't modify it directly.
106
-
107
- export const routes = ${JSON.stringify(routes, null, 2)}
145
+ ${typeDefinitions}
146
+ export const routes${routesType} = ${JSON.stringify(routes, null, 2)}
108
147
  `;
109
148
  routesStr = routesStr.replace(/"##(.*)##"/g, (_, p1) => `async () => ({...(await import('${p1.split("@@")[0]}')).default, name: '${p1.split("@@")[1]}'})`);
110
- routesStr = await prettier.format(routesStr, { parser: "babel", semi: false, singleQuote: true });
149
+ const parser = isTypeScript ? "typescript" : "babel";
150
+ routesStr = await prettier.format(routesStr, { parser, semi: false, singleQuote: true });
111
151
  const filePath = path.resolve(rootDir, routesPath);
112
152
  await fs.ensureDir(path.dirname(filePath));
113
153
  fs.writeFileSync(filePath, routesStr);
@@ -118,6 +158,9 @@ function VitePluginGeneroutes(options = {}) {
118
158
  name: "vite-plugin-generoutes",
119
159
  async configResolved(config) {
120
160
  rootDir = config.root;
161
+ const isTs = detectTypeScriptProject();
162
+ routesPath = options.routesPath || (isTs ? "src/router/routes.ts" : "src/router/routes.js");
163
+ isTypeScript = routesPath.endsWith(".ts");
121
164
  await writerRoutesFile(true);
122
165
  },
123
166
  configureServer(server) {
@@ -162,5 +205,6 @@ function parseDefineOptions(filePath, content) {
162
205
  }
163
206
  var index_default = VitePluginGeneroutes;
164
207
  export {
208
+ VitePluginGeneroutes,
165
209
  index_default as default
166
210
  };
package/package.json CHANGED
@@ -1,82 +1,89 @@
1
- {
2
- "name": "vite-plugin-generoutes",
3
- "type": "module",
4
- "version": "1.0.1",
5
- "packageManager": "pnpm@10.6.2",
6
- "description": "A Vite plugin that generate routes based on the file structure, supports dynamic routes, and supports custom meta data for each route.",
7
- "author": "Ronnie Zhang <zclzone@outlook.com>",
8
- "license": "MIT",
9
- "homepage": "https://github.com/zclzone/vite-plugin-generoutes",
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/zclzone/vite-plugin-generoutes.git"
13
- },
14
- "bugs": "https://github.com/zclzone/vite-plugin-generoutes/issues",
15
- "keywords": [],
16
- "sideEffects": false,
17
- "exports": {
18
- ".": {
19
- "types": "./dist/index.d.ts",
20
- "import": "./dist/index.js"
21
- }
22
- },
23
- "main": "./dist/index.js",
24
- "module": "./dist/index.js",
25
- "types": "./dist/index.d.ts",
26
- "typesVersions": {
27
- "*": {
28
- "*": [
29
- "./dist/*",
30
- "./dist/index.d.ts"
31
- ]
32
- }
33
- },
34
- "files": [
35
- "dist"
36
- ],
37
- "scripts": {
38
- "start": "tsup --watch",
39
- "build": "tsup",
40
- "lint": "eslint .",
41
- "prepublishOnly": "nr build",
42
- "release": "bumpp && npm publish",
43
- "test": "vitest",
44
- "typecheck": "tsc --noEmit",
45
- "prepare": "simple-git-hooks",
46
- "up:deps": "taze major -I"
47
- },
48
- "peerDependencies": {
49
- "vite": "^6.1.0"
50
- },
51
- "dependencies": {
52
- "@antfu/utils": "^9.1.0",
53
- "@vue/compiler-sfc": "^3.5.13",
54
- "chalk": "^5.4.1",
55
- "fs-extra": "^11.3.0",
56
- "glob": "^11.0.1",
57
- "prettier": "^3.5.3"
58
- },
59
- "devDependencies": {
60
- "@antfu/eslint-config": "^4.10.1",
61
- "@types/fs-extra": "^11.0.4",
62
- "@types/node": "^20.17.24",
63
- "bumpp": "^10.1.0",
64
- "eslint": "^9.22.0",
65
- "esno": "^4.8.0",
66
- "lint-staged": "^15.5.0",
67
- "pnpm": "^10.6.2",
68
- "rimraf": "^5.0.10",
69
- "simple-git-hooks": "^2.11.1",
70
- "taze": "^19.0.2",
71
- "tsup": "^8.4.0",
72
- "typescript": "^5.8.2",
73
- "unbuild": "^3.5.0",
74
- "vitest": "^3.0.8"
75
- },
76
- "simple-git-hooks": {
77
- "pre-commit": "pnpm lint-staged"
78
- },
79
- "lint-staged": {
80
- "*": "eslint --fix"
81
- }
82
- }
1
+ {
2
+ "name": "vite-plugin-generoutes",
3
+ "type": "module",
4
+ "version": "1.1.0-beta.3",
5
+ "packageManager": "pnpm@10.6.2",
6
+ "description": "A Vite plugin that generate routes based on the file structure, supports dynamic routes, and supports custom meta data for each route.",
7
+ "author": "Ronnie Zhang <zclzone@outlook.com>",
8
+ "license": "MIT",
9
+ "homepage": "https://github.com/zclzone/vite-plugin-generoutes",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/zclzone/vite-plugin-generoutes.git"
13
+ },
14
+ "bugs": "https://github.com/zclzone/vite-plugin-generoutes/issues",
15
+ "keywords": [],
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "main": "./dist/index.js",
24
+ "module": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "typesVersions": {
27
+ "*": {
28
+ "*": [
29
+ "./dist/*",
30
+ "./dist/index.d.ts"
31
+ ]
32
+ }
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "scripts": {
38
+ "start": "tsup --watch",
39
+ "build": "tsup",
40
+ "lint": "eslint .",
41
+ "prepublishOnly": "nr build",
42
+ "release": "bumpp && npm publish",
43
+ "test": "vitest",
44
+ "typecheck": "tsc --noEmit",
45
+ "prepare": "simple-git-hooks",
46
+ "up:deps": "taze major -I"
47
+ },
48
+ "peerDependencies": {
49
+ "vite": "^6.1.0",
50
+ "vue-router": "^4.0.0"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "vue-router": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "dependencies": {
58
+ "@antfu/utils": "^9.1.0",
59
+ "@vue/compiler-sfc": "^3.5.13",
60
+ "chalk": "^5.4.1",
61
+ "fs-extra": "^11.3.0",
62
+ "glob": "^11.0.1",
63
+ "prettier": "^3.5.3"
64
+ },
65
+ "devDependencies": {
66
+ "@antfu/eslint-config": "^4.10.1",
67
+ "@types/fs-extra": "^11.0.4",
68
+ "@types/node": "^20.17.24",
69
+ "bumpp": "^10.1.0",
70
+ "eslint": "^9.22.0",
71
+ "esno": "^4.8.0",
72
+ "lint-staged": "^15.5.0",
73
+ "pnpm": "^10.6.2",
74
+ "rimraf": "^5.0.10",
75
+ "simple-git-hooks": "^2.11.1",
76
+ "taze": "^19.0.2",
77
+ "tsup": "^8.4.0",
78
+ "typescript": "^5.8.2",
79
+ "unbuild": "^3.5.0",
80
+ "vitest": "^3.0.8",
81
+ "vue-router": "^4.5.0"
82
+ },
83
+ "simple-git-hooks": {
84
+ "pre-commit": "pnpm lint-staged"
85
+ },
86
+ "lint-staged": {
87
+ "*": "eslint --fix"
88
+ }
89
+ }