next-vite-router 1.0.5 → 1.0.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.
Files changed (3) hide show
  1. package/README.md +247 -247
  2. package/dist/cli.cjs +20 -9
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,248 +1,248 @@
1
- # Next Vite Router
2
-
3
- Next Vite Router is an npm package that provides Next.js-style, file-based routing for React applications built with Vite. It generates React Router route objects from a filesystem layout (pages, layouts, not-found), and it exposes a Vite plugin that injects a virtual module to generate routes at build/dev time.
4
-
5
- ## Installation
6
-
7
- Install with your package manager of choice:
8
-
9
- ```bash
10
- pnpm add next-vite-router
11
- # or
12
- npm install next-vite-router
13
- # or
14
- yarn add next-vite-router
15
- ```
16
-
17
- The package has peer dependencies: React, React DOM and React Router DOM. Make sure your project already includes compatible versions (React 18+ is recommended).
18
-
19
- ## CLI / Getting Started
20
-
21
- The quickest way to start a new project with `next-vite-router` is to use the interactive CLI:
22
-
23
- ```bash
24
- npx next-vite-router init
25
- # or
26
- pnpm dlx next-vite-router init
27
- # or
28
- yarn dlx next-vite-router init
29
- # or
30
- bunx next-vite-router init
31
- ```
32
-
33
- The CLI will prompt you for:
34
-
35
- 1. **Project name** name of the folder to create
36
- 2. **Template** which React Vite variant to use:
37
- - `react-ts` (React + TypeScript)
38
- - `react-swc-ts` (React + SWC + TypeScript)
39
- - `react-compiler-ts` (React Compiler + TypeScript)
40
- 3. **Src folder** whether to keep source files in `src/` (recommended) or place them at the project root
41
- 4. **Tailwind CSS** whether to add and configure Tailwind CSS (with `@tailwindcss/vite`)
42
-
43
- ### What the CLI does
44
-
45
- The CLI automates the entire setup:
46
-
47
- - Scaffolds a new Vite + React project using `create-vite`
48
- - Installs `next-vite-router` and `react-router-dom@latest`
49
- - Configures the Vite plugin in `vite.config.ts`
50
- - Sets up path aliases (`@/*`) in `tsconfig.json` and Vite config
51
- - Creates TypeScript declarations for the virtual module (`virtual:next-vite-router`)
52
- - Generates example pages (`app/page.tsx`, `app/layout.tsx`, `app/example/page.tsx`)
53
- - Optionally configures Tailwind CSS with `@tailwindcss/vite` and creates `global.css`
54
-
55
- After the CLI finishes:
56
-
57
- ```bash
58
- cd <your-project-name>
59
- pnpm dev
60
- ```
61
-
62
- Your app is ready with file-based routing!
63
-
64
- ## Quick Start Vite plugin
65
-
66
- The recommended and easiest way to use this library in a Vite app is via the Vite plugin. The plugin exposes a virtual module `virtual:next-vite-router` that provides a `generateRoutes()` function and re-exports `useRoutes` from `react-router-dom` for convenience.
67
-
68
- Example `vite.config.ts`:
69
-
70
- ```ts
71
- import { defineConfig } from 'vite';
72
- import react from '@vitejs/plugin-react';
73
- import { nextViteRouter } from 'next-vite-router';
74
-
75
- export default defineConfig({
76
- plugins: [
77
- react(),
78
- nextViteRouter({ pagesDir: 'src/pages' })
79
- ]
80
- });
81
- ```
82
-
83
- Example usage inside your app. **Important: generate routes once at module level** (not inside the component) to avoid infinite re-renders.
84
-
85
- File: `src/App.tsx`
86
-
87
- ```tsx
88
- import { useRoutes } from 'react-router-dom';
89
- import { generateRoutes } from 'virtual:next-vite-router';
90
-
91
- const routes = generateRoutes();
92
-
93
- export default function App() {
94
- const element = useRoutes(routes);
95
- return element;
96
- }
97
- ```
98
-
99
- File: `src/main.tsx`
100
-
101
- ```tsx
102
- import { StrictMode } from 'react';
103
- import { createRoot } from 'react-dom/client';
104
- import { BrowserRouter } from 'react-router-dom';
105
- import App from './App';
106
-
107
- createRoot(document.getElementById('root')!).render(
108
- <StrictMode>
109
- <BrowserRouter>
110
- <App />
111
- </BrowserRouter>
112
- </StrictMode>
113
- );
114
- ```
115
-
116
- **Key points:**
117
-
118
- - Call `generateRoutes()` once at module level, not inside the component (prevents infinite re-renders).
119
- - Wrap your app with `BrowserRouter` at the entry point (`main.tsx`), not inside `App`.
120
- - `pagesDir` (default: `src/app`) is the directory where you organize your **route files** (`page.tsx`, `layout.tsx`, `not-found.tsx`). It has nothing to do with the `App.tsx` component.
121
- - The virtual module is `virtual:next-vite-router` (the plugin resolves it internally).
122
-
123
- **Example file structure:**
124
-
125
- ```
126
- src/
127
- ├── App.tsx ← Your main app component
128
- ├── main.tsx ← Entry point (with BrowserRouter)
129
- └── app/ ← pagesDir (routes are organized here)
130
- ├── page.tsx ← Home page
131
- ├── layout.tsx ← Root layout
132
- └── dashboard/
133
- ├── page.tsx ← /dashboard page
134
- └── layout.tsx ← Dashboard layout
135
- ```
136
-
137
- TypeScript note:
138
-
139
- If you're using TypeScript in a consuming project, add a declaration file so the virtual module is recognized by the compiler. Create a file such as `src/virtual.d.ts` (or any `*.d.ts` included by your `tsconfig.json`) with the following content:
140
-
141
- ```ts
142
- declare module 'virtual:next-vite-router' {
143
- import type { RouteObject } from 'react-router-dom';
144
-
145
- export const generateRoutes: () => RouteObject[];
146
- export { useRoutes } from 'react-router-dom';
147
- }
148
- ```
149
-
150
- This ensures TypeScript knows the shape of the virtual module provided by the Vite plugin and avoids `Cannot find module 'virtual:next-vite-router'` errors in editors and builds.
151
-
152
- ## Programmatic route generation
153
-
154
- If you prefer to generate routes manually (for custom setups), the package exports helpers you can use with `import.meta.glob`.
155
-
156
- Example:
157
-
158
- ```ts
159
- import { createRouteGenerator } from 'next-vite-router';
160
-
161
- // in a Vite environment
162
- const pages = import.meta.glob('../../pages/**/page.tsx');
163
- const layouts = import.meta.glob('../../pages/**/layout.tsx', { eager: true });
164
- const notFounds = import.meta.glob('../../pages/**/not-found.tsx');
165
-
166
- const generateRoutes = createRouteGenerator(pages, layouts, notFounds);
167
- const routes = generateRoutes();
168
- ```
169
-
170
- Use this when you need a fully custom glob layout or want to call the generator at runtime.
171
-
172
- ## API Reference
173
-
174
- Exports from the package (see `src/index.ts`):
175
-
176
- - `createRouteGenerator(pages, layouts, notFounds)` returns a function that builds `RouteObject[]` using your globs.
177
- - `buildRouteTree` builds the intermediate route tree from page/layout/not-found globs.
178
- - `treeToRoutes` converts the route tree to React Router routes.
179
- - `registerMiddleware`, `clearMiddlewares` middleware helpers to manage registered middlewares.
180
- - `configureRouter` configure router-level options.
181
- - `nextViteRouter(options)` Vite plugin factory. Options:
182
- - `pagesDir?: string` (default: `src/app`)
183
- - `pageFile?: string` (default: `page.tsx`)
184
- - `layoutFile?: string` (default: `layout.tsx`)
185
- - `notFoundFile?: string` (default: `not-found.tsx`)
186
- - Types exported: `RouterConfig`, `RouteNode`, `RouteMiddleware`, `NextViteRouterPluginOptions`.
187
-
188
- ### `configureRouter(config: RouterConfig)`
189
-
190
- Use `configureRouter` to set global router options for runtime behavior. The function merges the provided `config` with any existing configuration.
191
-
192
- Common `RouterConfig` fields:
193
-
194
- - `loadingFallback?: React.ComponentType` component shown while lazy-loaded page components load.
195
- - `pagesDir?: string` path used by the generator to resolve pages (useful if you need to override defaults at runtime).
196
- - `enableLazyLoading?: boolean` when true, pages are wrapped to load lazily.
197
-
198
- Example:
199
-
200
- ```ts
201
- import { configureRouter } from 'next-vite-router';
202
-
203
- configureRouter({
204
- loadingFallback: () => <div>Loading...</div>,
205
- enableLazyLoading: true,
206
- });
207
- ```
208
-
209
- Call `configureRouter` during app bootstrap before calling `generateRoutes()`.
210
-
211
- ### `registerMiddleware(pattern: RegExp, middleware: RouteMiddleware)`
212
-
213
- `registerMiddleware` lets you register middleware functions that will be applied to route elements whose path matches the provided `pattern` (a `RegExp`). Middlewares receive the route element (`ReactElement`) and should return a new element (for example wrapping it with providers, guards, or layout components).
214
-
215
- Important details:
216
-
217
- - Middlewares are stored in insertion order and applied sequentially.
218
- - To remove all registered middlewares, use `clearMiddlewares()`.
219
- - The internal helper `applyMiddlewares(path, element)` is used when constructing the final route element.
220
-
221
- Example:
222
-
223
- ```ts
224
- import { registerMiddleware } from 'next-vite-router';
225
-
226
- registerMiddleware(/^\/dashboard/, (element) => (
227
- <AuthGuard>{element}</AuthGuard>
228
- ));
229
- ```
230
-
231
- ## Configuration options (plugin)
232
-
233
- The plugin takes an options object. Defaults are:
234
-
235
- ```ts
236
- {
237
- pagesDir: 'src/app',
238
- pageFile: 'page.tsx',
239
- layoutFile: 'layout.tsx',
240
- notFoundFile: 'not-found.tsx',
241
- }
242
- ```
243
-
244
- Pass a custom `pagesDir` if your project uses `src/pages` or another convention.
245
-
246
- ## License
247
-
1
+ # Next Vite Router
2
+
3
+ Next Vite Router is an npm package that provides Next.js-style, file-based routing for React applications built with Vite. It generates React Router route objects from a filesystem layout (pages, layouts, not-found), and it exposes a Vite plugin that injects a virtual module to generate routes at build/dev time.
4
+
5
+ ## Installation
6
+
7
+ Install with your package manager of choice:
8
+
9
+ ```bash
10
+ pnpm add next-vite-router
11
+ # or
12
+ npm install next-vite-router
13
+ # or
14
+ yarn add next-vite-router
15
+ ```
16
+
17
+ The package has peer dependencies: React, React DOM and React Router DOM. Make sure your project already includes compatible versions (React 18+ is recommended).
18
+
19
+ ## CLI / Getting Started
20
+
21
+ The quickest way to start a new project with `next-vite-router` is to use the interactive CLI:
22
+
23
+ ```bash
24
+ npx next-vite-router init
25
+ # or
26
+ pnpm dlx next-vite-router init
27
+ # or
28
+ yarn dlx next-vite-router init
29
+ # or
30
+ bunx next-vite-router init
31
+ ```
32
+
33
+ The CLI will prompt you for:
34
+
35
+ 1. **Project name** name of the folder to create
36
+ 2. **Template** which React Vite variant to use:
37
+ - `react-ts` (React + TypeScript)
38
+ - `react-swc-ts` (React + SWC + TypeScript)
39
+ - `react-compiler-ts` (React Compiler + TypeScript)
40
+ 3. **Src folder** whether to keep source files in `src/` (recommended) or place them at the project root
41
+ 4. **Tailwind CSS** whether to add and configure Tailwind CSS (with `@tailwindcss/vite`)
42
+
43
+ ### What the CLI does
44
+
45
+ The CLI automates the entire setup:
46
+
47
+ - Scaffolds a new Vite + React project using `create-vite`
48
+ - Installs `next-vite-router` and `react-router-dom@latest`
49
+ - Configures the Vite plugin in `vite.config.ts`
50
+ - Sets up path aliases (`@/*`) in `tsconfig.json` and Vite config
51
+ - Creates TypeScript declarations for the virtual module (`virtual:next-vite-router`)
52
+ - Generates example pages (`app/page.tsx`, `app/layout.tsx`, `app/example/page.tsx`)
53
+ - Optionally configures Tailwind CSS with `@tailwindcss/vite` and creates `global.css`
54
+
55
+ After the CLI finishes:
56
+
57
+ ```bash
58
+ cd <your-project-name>
59
+ pnpm dev
60
+ ```
61
+
62
+ Your app is ready with file-based routing!
63
+
64
+ ## Quick Start Vite plugin
65
+
66
+ The recommended and easiest way to use this library in a Vite app is via the Vite plugin. The plugin exposes a virtual module `virtual:next-vite-router` that provides a `generateRoutes()` function and re-exports `useRoutes` from `react-router-dom` for convenience.
67
+
68
+ Example `vite.config.ts`:
69
+
70
+ ```ts
71
+ import { defineConfig } from 'vite';
72
+ import react from '@vitejs/plugin-react';
73
+ import { nextViteRouter } from 'next-vite-router';
74
+
75
+ export default defineConfig({
76
+ plugins: [
77
+ react(),
78
+ nextViteRouter({ pagesDir: 'src/pages' })
79
+ ]
80
+ });
81
+ ```
82
+
83
+ Example usage inside your app. **Important: generate routes once at module level** (not inside the component) to avoid infinite re-renders.
84
+
85
+ File: `src/App.tsx`
86
+
87
+ ```tsx
88
+ import { useRoutes } from 'react-router-dom';
89
+ import { generateRoutes } from 'virtual:next-vite-router';
90
+
91
+ const routes = generateRoutes();
92
+
93
+ export default function App() {
94
+ const element = useRoutes(routes);
95
+ return element;
96
+ }
97
+ ```
98
+
99
+ File: `src/main.tsx`
100
+
101
+ ```tsx
102
+ import { StrictMode } from 'react';
103
+ import { createRoot } from 'react-dom/client';
104
+ import { BrowserRouter } from 'react-router-dom';
105
+ import App from './App';
106
+
107
+ createRoot(document.getElementById('root')!).render(
108
+ <StrictMode>
109
+ <BrowserRouter>
110
+ <App />
111
+ </BrowserRouter>
112
+ </StrictMode>
113
+ );
114
+ ```
115
+
116
+ **Key points:**
117
+
118
+ - Call `generateRoutes()` once at module level, not inside the component (prevents infinite re-renders).
119
+ - Wrap your app with `BrowserRouter` at the entry point (`main.tsx`), not inside `App`.
120
+ - `pagesDir` (default: `src/app`) is the directory where you organize your **route files** (`page.tsx`, `layout.tsx`, `not-found.tsx`). It has nothing to do with the `App.tsx` component.
121
+ - The virtual module is `virtual:next-vite-router` (the plugin resolves it internally).
122
+
123
+ **Example file structure:**
124
+
125
+ ```
126
+ src/
127
+ ├── App.tsx ← Your main app component
128
+ ├── main.tsx ← Entry point (with BrowserRouter)
129
+ └── app/ ← pagesDir (routes are organized here)
130
+ ├── page.tsx ← Home page
131
+ ├── layout.tsx ← Root layout
132
+ └── dashboard/
133
+ ├── page.tsx ← /dashboard page
134
+ └── layout.tsx ← Dashboard layout
135
+ ```
136
+
137
+ TypeScript note:
138
+
139
+ If you're using TypeScript in a consuming project, add a declaration file so the virtual module is recognized by the compiler. Create a file such as `src/virtual.d.ts` (or any `*.d.ts` included by your `tsconfig.json`) with the following content:
140
+
141
+ ```ts
142
+ declare module 'virtual:next-vite-router' {
143
+ import type { RouteObject } from 'react-router-dom';
144
+
145
+ export const generateRoutes: () => RouteObject[];
146
+ export { useRoutes } from 'react-router-dom';
147
+ }
148
+ ```
149
+
150
+ This ensures TypeScript knows the shape of the virtual module provided by the Vite plugin and avoids `Cannot find module 'virtual:next-vite-router'` errors in editors and builds.
151
+
152
+ ## Programmatic route generation
153
+
154
+ If you prefer to generate routes manually (for custom setups), the package exports helpers you can use with `import.meta.glob`.
155
+
156
+ Example:
157
+
158
+ ```ts
159
+ import { createRouteGenerator } from 'next-vite-router';
160
+
161
+ // in a Vite environment
162
+ const pages = import.meta.glob('../../pages/**/page.tsx');
163
+ const layouts = import.meta.glob('../../pages/**/layout.tsx', { eager: true });
164
+ const notFounds = import.meta.glob('../../pages/**/not-found.tsx');
165
+
166
+ const generateRoutes = createRouteGenerator(pages, layouts, notFounds);
167
+ const routes = generateRoutes();
168
+ ```
169
+
170
+ Use this when you need a fully custom glob layout or want to call the generator at runtime.
171
+
172
+ ## API Reference
173
+
174
+ Exports from the package (see `src/index.ts`):
175
+
176
+ - `createRouteGenerator(pages, layouts, notFounds)` returns a function that builds `RouteObject[]` using your globs.
177
+ - `buildRouteTree` builds the intermediate route tree from page/layout/not-found globs.
178
+ - `treeToRoutes` converts the route tree to React Router routes.
179
+ - `registerMiddleware`, `clearMiddlewares` middleware helpers to manage registered middlewares.
180
+ - `configureRouter` configure router-level options.
181
+ - `nextViteRouter(options)` Vite plugin factory. Options:
182
+ - `pagesDir?: string` (default: `src/app`)
183
+ - `pageFile?: string` (default: `page.tsx`)
184
+ - `layoutFile?: string` (default: `layout.tsx`)
185
+ - `notFoundFile?: string` (default: `not-found.tsx`)
186
+ - Types exported: `RouterConfig`, `RouteNode`, `RouteMiddleware`, `NextViteRouterPluginOptions`.
187
+
188
+ ### `configureRouter(config: RouterConfig)`
189
+
190
+ Use `configureRouter` to set global router options for runtime behavior. The function merges the provided `config` with any existing configuration.
191
+
192
+ Common `RouterConfig` fields:
193
+
194
+ - `loadingFallback?: React.ComponentType` component shown while lazy-loaded page components load.
195
+ - `pagesDir?: string` path used by the generator to resolve pages (useful if you need to override defaults at runtime).
196
+ - `enableLazyLoading?: boolean` when true, pages are wrapped to load lazily.
197
+
198
+ Example:
199
+
200
+ ```ts
201
+ import { configureRouter } from 'next-vite-router';
202
+
203
+ configureRouter({
204
+ loadingFallback: () => <div>Loading...</div>,
205
+ enableLazyLoading: true,
206
+ });
207
+ ```
208
+
209
+ Call `configureRouter` during app bootstrap before calling `generateRoutes()`.
210
+
211
+ ### `registerMiddleware(pattern: RegExp, middleware: RouteMiddleware)`
212
+
213
+ `registerMiddleware` lets you register middleware functions that will be applied to route elements whose path matches the provided `pattern` (a `RegExp`). Middlewares receive the route element (`ReactElement`) and should return a new element (for example wrapping it with providers, guards, or layout components).
214
+
215
+ Important details:
216
+
217
+ - Middlewares are stored in insertion order and applied sequentially.
218
+ - To remove all registered middlewares, use `clearMiddlewares()`.
219
+ - The internal helper `applyMiddlewares(path, element)` is used when constructing the final route element.
220
+
221
+ Example:
222
+
223
+ ```ts
224
+ import { registerMiddleware } from 'next-vite-router';
225
+
226
+ registerMiddleware(/^\/dashboard/, (element) => (
227
+ <AuthGuard>{element}</AuthGuard>
228
+ ));
229
+ ```
230
+
231
+ ## Configuration options (plugin)
232
+
233
+ The plugin takes an options object. Defaults are:
234
+
235
+ ```ts
236
+ {
237
+ pagesDir: 'src/app',
238
+ pageFile: 'page.tsx',
239
+ layoutFile: 'layout.tsx',
240
+ notFoundFile: 'not-found.tsx',
241
+ }
242
+ ```
243
+
244
+ Pass a custom `pagesDir` if your project uses `src/pages` or another convention.
245
+
246
+ ## License
247
+
248
248
  MIT
package/dist/cli.cjs CHANGED
@@ -147,17 +147,30 @@ function stripJsonComments(jsonString) {
147
147
  jsonString = jsonString.replace(/,(\s*[}\]])/g, "$1");
148
148
  return jsonString;
149
149
  }
150
- function updateAppTsConfig(projectDir) {
150
+ function updateAppTsConfig(projectDir, src) {
151
151
  const tsConfigAppPath = path.join(projectDir, "tsconfig.app.json");
152
152
  if (!fs.existsSync(tsConfigAppPath)) return;
153
153
  const content = fs.readFileSync(tsConfigAppPath, "utf-8");
154
154
  const cleanedContent = stripJsonComments(content);
155
155
  const tsConfigApp = JSON.parse(cleanedContent);
156
- tsConfigApp.include = [
157
- "./**/*.ts",
158
- "./**/*.tsx",
159
- "virtual-next-vite-router.d.ts"
160
- ];
156
+ const aliasPath = src ? "./src/*" : "./*";
157
+ tsConfigApp.compilerOptions = {
158
+ ...tsConfigApp.compilerOptions,
159
+ baseUrl: ".",
160
+ paths: {
161
+ ...tsConfigApp.compilerOptions?.paths,
162
+ "@/*": [aliasPath]
163
+ }
164
+ };
165
+ if (!src) {
166
+ tsConfigApp.include = [
167
+ "./**/*.ts",
168
+ "./**/*.tsx",
169
+ "virtual-next-vite-router.d.ts"
170
+ ];
171
+ } else {
172
+ tsConfigApp.include = ["src"];
173
+ }
161
174
  fs.writeFileSync(
162
175
  tsConfigAppPath,
163
176
  JSON.stringify(tsConfigApp, null, 2),
@@ -355,9 +368,7 @@ function startNextViteRouterConfig({
355
368
  fs.rmSync(srcPath, { recursive: true, force: true });
356
369
  }
357
370
  updateTsConfigJson(projectDir, src);
358
- if (!src) {
359
- updateAppTsConfig(projectDir);
360
- }
371
+ updateAppTsConfig(projectDir, src);
361
372
  createVirtualDTS(projectDir, src);
362
373
  createMainTSX(projectDir, src);
363
374
  if (tailwindcss) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-vite-router",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "Next.js-like file-based routing for React + Vite",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",