next-vite-router 1.0.4 → 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 -202
  2. package/dist/cli.cjs +538 -0
  3. package/package.json +13 -3
package/README.md CHANGED
@@ -1,203 +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
- ## Quick Start Vite plugin
20
-
21
- 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.
22
-
23
- Example `vite.config.ts`:
24
-
25
- ```ts
26
- import { defineConfig } from 'vite';
27
- import react from '@vitejs/plugin-react';
28
- import { nextViteRouter } from 'next-vite-router';
29
-
30
- export default defineConfig({
31
- plugins: [
32
- react(),
33
- nextViteRouter({ pagesDir: 'src/pages' })
34
- ]
35
- });
36
- ```
37
-
38
- Example usage inside your app. **Important: generate routes once at module level** (not inside the component) to avoid infinite re-renders.
39
-
40
- File: `src/App.tsx`
41
-
42
- ```tsx
43
- import { useRoutes } from 'react-router-dom';
44
- import { generateRoutes } from 'virtual:next-vite-router';
45
-
46
- const routes = generateRoutes();
47
-
48
- export default function App() {
49
- const element = useRoutes(routes);
50
- return element;
51
- }
52
- ```
53
-
54
- File: `src/main.tsx`
55
-
56
- ```tsx
57
- import { StrictMode } from 'react';
58
- import { createRoot } from 'react-dom/client';
59
- import { BrowserRouter } from 'react-router-dom';
60
- import App from './App';
61
-
62
- createRoot(document.getElementById('root')!).render(
63
- <StrictMode>
64
- <BrowserRouter>
65
- <App />
66
- </BrowserRouter>
67
- </StrictMode>
68
- );
69
- ```
70
-
71
- **Key points:**
72
-
73
- - Call `generateRoutes()` once at module level, not inside the component (prevents infinite re-renders).
74
- - Wrap your app with `BrowserRouter` at the entry point (`main.tsx`), not inside `App`.
75
- - `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.
76
- - The virtual module is `virtual:next-vite-router` (the plugin resolves it internally).
77
-
78
- **Example file structure:**
79
-
80
- ```
81
- src/
82
- ├── App.tsx ← Your main app component
83
- ├── main.tsx ← Entry point (with BrowserRouter)
84
- └── app/ ← pagesDir (routes are organized here)
85
- ├── page.tsx ← Home page
86
- ├── layout.tsx ← Root layout
87
- └── dashboard/
88
- ├── page.tsx ← /dashboard page
89
- └── layout.tsx ← Dashboard layout
90
- ```
91
-
92
- TypeScript note:
93
-
94
- 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:
95
-
96
- ```ts
97
- declare module 'virtual:next-vite-router' {
98
- import type { RouteObject } from 'react-router-dom';
99
-
100
- export const generateRoutes: () => RouteObject[];
101
- export { useRoutes } from 'react-router-dom';
102
- }
103
- ```
104
-
105
- 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.
106
-
107
- ## Programmatic route generation
108
-
109
- If you prefer to generate routes manually (for custom setups), the package exports helpers you can use with `import.meta.glob`.
110
-
111
- Example:
112
-
113
- ```ts
114
- import { createRouteGenerator } from 'next-vite-router';
115
-
116
- // in a Vite environment
117
- const pages = import.meta.glob('../../pages/**/page.tsx');
118
- const layouts = import.meta.glob('../../pages/**/layout.tsx', { eager: true });
119
- const notFounds = import.meta.glob('../../pages/**/not-found.tsx');
120
-
121
- const generateRoutes = createRouteGenerator(pages, layouts, notFounds);
122
- const routes = generateRoutes();
123
- ```
124
-
125
- Use this when you need a fully custom glob layout or want to call the generator at runtime.
126
-
127
- ## API Reference
128
-
129
- Exports from the package (see `src/index.ts`):
130
-
131
- - `createRouteGenerator(pages, layouts, notFounds)` returns a function that builds `RouteObject[]` using your globs.
132
- - `buildRouteTree` builds the intermediate route tree from page/layout/not-found globs.
133
- - `treeToRoutes` converts the route tree to React Router routes.
134
- - `registerMiddleware`, `clearMiddlewares` middleware helpers to manage registered middlewares.
135
- - `configureRouter` configure router-level options.
136
- - `nextViteRouter(options)` Vite plugin factory. Options:
137
- - `pagesDir?: string` (default: `src/app`)
138
- - `pageFile?: string` (default: `page.tsx`)
139
- - `layoutFile?: string` (default: `layout.tsx`)
140
- - `notFoundFile?: string` (default: `not-found.tsx`)
141
- - Types exported: `RouterConfig`, `RouteNode`, `RouteMiddleware`, `NextViteRouterPluginOptions`.
142
-
143
- ### `configureRouter(config: RouterConfig)`
144
-
145
- Use `configureRouter` to set global router options for runtime behavior. The function merges the provided `config` with any existing configuration.
146
-
147
- Common `RouterConfig` fields:
148
-
149
- - `loadingFallback?: React.ComponentType` component shown while lazy-loaded page components load.
150
- - `pagesDir?: string` path used by the generator to resolve pages (useful if you need to override defaults at runtime).
151
- - `enableLazyLoading?: boolean` when true, pages are wrapped to load lazily.
152
-
153
- Example:
154
-
155
- ```ts
156
- import { configureRouter } from 'next-vite-router';
157
-
158
- configureRouter({
159
- loadingFallback: () => <div>Loading...</div>,
160
- enableLazyLoading: true,
161
- });
162
- ```
163
-
164
- Call `configureRouter` during app bootstrap before calling `generateRoutes()`.
165
-
166
- ### `registerMiddleware(pattern: RegExp, middleware: RouteMiddleware)`
167
-
168
- `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).
169
-
170
- Important details:
171
-
172
- - Middlewares are stored in insertion order and applied sequentially.
173
- - To remove all registered middlewares, use `clearMiddlewares()`.
174
- - The internal helper `applyMiddlewares(path, element)` is used when constructing the final route element.
175
-
176
- Example:
177
-
178
- ```ts
179
- import { registerMiddleware } from 'next-vite-router';
180
-
181
- registerMiddleware(/^\/dashboard/, (element) => (
182
- <AuthGuard>{element}</AuthGuard>
183
- ));
184
- ```
185
-
186
- ## Configuration options (plugin)
187
-
188
- The plugin takes an options object. Defaults are:
189
-
190
- ```ts
191
- {
192
- pagesDir: 'src/app',
193
- pageFile: 'page.tsx',
194
- layoutFile: 'layout.tsx',
195
- notFoundFile: 'not-found.tsx',
196
- }
197
- ```
198
-
199
- Pass a custom `pagesDir` if your project uses `src/pages` or another convention.
200
-
201
- ## License
202
-
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
+
203
248
  MIT
package/dist/cli.cjs ADDED
@@ -0,0 +1,538 @@
1
+ "use strict";
2
+ const commander = require("commander");
3
+ const node_child_process = require("node:child_process");
4
+ const child_process = require("child_process");
5
+ const prompts = require("prompts");
6
+ const fs = require("fs");
7
+ const path = require("path");
8
+ function isAvailable(cmd) {
9
+ try {
10
+ node_child_process.execSync(`${cmd} --version`, { stdio: "ignore" });
11
+ return true;
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+ function detectFromUserAgent() {
17
+ const ua = process.env.npm_config_user_agent;
18
+ if (!ua) return null;
19
+ if (ua.startsWith("pnpm")) return "pnpm";
20
+ if (ua.startsWith("bun")) return "bun";
21
+ if (ua.startsWith("yarn")) return "yarn";
22
+ if (ua.startsWith("npm")) return "npm";
23
+ return null;
24
+ }
25
+ function detectPackageManager() {
26
+ const preferred = process.env.PREFERRED_PM ?? void 0;
27
+ const fromUA = detectFromUserAgent();
28
+ const candidates = [];
29
+ if (fromUA) candidates.push(fromUA);
30
+ if (preferred && !candidates.includes(preferred)) candidates.push(preferred);
31
+ ["pnpm", "bun", "yarn", "npm"].forEach((p) => {
32
+ const pm2 = p;
33
+ if (!candidates.includes(pm2)) candidates.push(pm2);
34
+ });
35
+ let chosen = null;
36
+ for (const pm2 of candidates) {
37
+ if (isAvailable(pm2)) {
38
+ chosen = pm2;
39
+ break;
40
+ }
41
+ }
42
+ if (!chosen) {
43
+ chosen = "npm";
44
+ }
45
+ switch (chosen) {
46
+ case "pnpm":
47
+ return {
48
+ name: "pnpm",
49
+ createProjectCommand: (projectName, template) => `pnpm create vite@latest ${projectName} --template ${template} --no-rolldown`,
50
+ addDepsCommand: (deps) => `pnpm add ${deps.join(" ")}`,
51
+ addDevDepsCommand: (deps) => `pnpm add -D ${deps.join(" ")}`,
52
+ installCommand: "pnpm install"
53
+ };
54
+ case "bun":
55
+ return {
56
+ name: "bun",
57
+ createProjectCommand: (projectName, template) => `bun create vite ${projectName} --template=${template} --no-rolldown`,
58
+ addDepsCommand: (deps) => `bun add ${deps.join(" ")}`,
59
+ addDevDepsCommand: (deps) => `bun add -d ${deps.join(" ")}`,
60
+ installCommand: "bun install"
61
+ };
62
+ case "yarn":
63
+ return {
64
+ name: "yarn",
65
+ createProjectCommand: (projectName, template) => `yarn create vite ${projectName} --template=${template} --no-rolldown`,
66
+ addDepsCommand: (deps) => `yarn add ${deps.join(" ")}`,
67
+ addDevDepsCommand: (deps) => `yarn add -D ${deps.join(" ")}`,
68
+ installCommand: "yarn install"
69
+ };
70
+ case "npm":
71
+ default:
72
+ return {
73
+ name: "npm",
74
+ createProjectCommand: (projectName, template) => `npm create vite@latest ${projectName} -- --template ${template} --no-rolldown`,
75
+ addDepsCommand: (deps) => `npm install ${deps.join(" ")}`,
76
+ addDevDepsCommand: (deps) => `npm install -D ${deps.join(" ")}`,
77
+ installCommand: "npm install"
78
+ };
79
+ }
80
+ }
81
+ let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = true;
82
+ if (typeof process !== "undefined") {
83
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
84
+ isTTY = process.stdout && process.stdout.isTTY;
85
+ }
86
+ const $ = {
87
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY)
88
+ };
89
+ function init$1(x, y) {
90
+ let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
91
+ let open = `\x1B[${x}m`, close = `\x1B[${y}m`;
92
+ return function(txt) {
93
+ if (!$.enabled || txt == null) return txt;
94
+ return open + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
95
+ };
96
+ }
97
+ const red = init$1(31, 39);
98
+ const green = init$1(32, 39);
99
+ const yellow = init$1(33, 39);
100
+ const cyan = init$1(36, 39);
101
+ const highlighter = {
102
+ error: red,
103
+ warn: yellow,
104
+ info: cyan,
105
+ success: green
106
+ };
107
+ const logger = {
108
+ error(...args) {
109
+ console.log(highlighter.error(args.join(" ")));
110
+ },
111
+ warn(...args) {
112
+ console.log(highlighter.warn(args.join(" ")));
113
+ },
114
+ info(...args) {
115
+ console.log(highlighter.info(args.join(" ")));
116
+ },
117
+ success(...args) {
118
+ console.log(highlighter.success(args.join(" ")));
119
+ },
120
+ log(...args) {
121
+ console.log(args.join(" "));
122
+ },
123
+ break() {
124
+ console.log("");
125
+ }
126
+ };
127
+ function getViteConfigPath(projectDir) {
128
+ const tsPath = path.join(projectDir, "vite.config.ts");
129
+ const jsPath = path.join(projectDir, "vite.config.js");
130
+ if (fs.existsSync(tsPath)) return tsPath;
131
+ if (fs.existsSync(jsPath)) return jsPath;
132
+ return null;
133
+ }
134
+ function readViteConfig(projectDir) {
135
+ const configPath = getViteConfigPath(projectDir);
136
+ if (!configPath) return null;
137
+ return fs.readFileSync(configPath, "utf-8");
138
+ }
139
+ function writeViteConfig(projectDir, content) {
140
+ const configPath = getViteConfigPath(projectDir);
141
+ if (!configPath) throw new Error("Vite config not found");
142
+ fs.writeFileSync(configPath, content, "utf-8");
143
+ }
144
+ function stripJsonComments(jsonString) {
145
+ jsonString = jsonString.replace(/\/\/.*$/gm, "");
146
+ jsonString = jsonString.replace(/\/\*[\s\S]*?\*\//g, "");
147
+ jsonString = jsonString.replace(/,(\s*[}\]])/g, "$1");
148
+ return jsonString;
149
+ }
150
+ function updateAppTsConfig(projectDir, src) {
151
+ const tsConfigAppPath = path.join(projectDir, "tsconfig.app.json");
152
+ if (!fs.existsSync(tsConfigAppPath)) return;
153
+ const content = fs.readFileSync(tsConfigAppPath, "utf-8");
154
+ const cleanedContent = stripJsonComments(content);
155
+ const tsConfigApp = JSON.parse(cleanedContent);
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
+ }
174
+ fs.writeFileSync(
175
+ tsConfigAppPath,
176
+ JSON.stringify(tsConfigApp, null, 2),
177
+ "utf-8"
178
+ );
179
+ }
180
+ function updateTsConfigJson(projectDir, src) {
181
+ const tsConfigPath = path.join(projectDir, "tsconfig.json");
182
+ if (!fs.existsSync(tsConfigPath)) return;
183
+ const content = fs.readFileSync(tsConfigPath, "utf-8");
184
+ const cleanedContent = stripJsonComments(content);
185
+ const tsConfig = JSON.parse(cleanedContent);
186
+ if (!tsConfig.compilerOptions) {
187
+ tsConfig.compilerOptions = {};
188
+ }
189
+ tsConfig.compilerOptions.baseUrl = ".";
190
+ tsConfig.compilerOptions.paths = {
191
+ "@/*": [src ? "./src/*" : "./*"]
192
+ };
193
+ fs.writeFileSync(tsConfigPath, JSON.stringify(tsConfig, null, 2), "utf-8");
194
+ }
195
+ function createVirtualDTS(projectDir, useSrc) {
196
+ const targetDir = useSrc ? path.join(projectDir, "src") : projectDir;
197
+ if (useSrc && !fs.existsSync(targetDir)) {
198
+ fs.mkdirSync(targetDir, { recursive: true });
199
+ }
200
+ const filePath = path.join(targetDir, "virtual-next-vite-router.d.ts");
201
+ const content = `declare module 'virtual:next-vite-router' {
202
+ import type { RouteObject } from 'react-router-dom';
203
+
204
+ export const generateRoutes: () => RouteObject[];
205
+ export { useRoutes } from 'react-router-dom';
206
+ }
207
+ `;
208
+ fs.writeFileSync(filePath, content, "utf-8");
209
+ }
210
+ function createMainTSX(projectDir, useSrc) {
211
+ const targetDir = useSrc ? path.join(projectDir, "src") : projectDir;
212
+ if (useSrc && !fs.existsSync(targetDir)) {
213
+ fs.mkdirSync(targetDir, { recursive: true });
214
+ }
215
+ const mainPath = path.join(targetDir, "main.tsx");
216
+ const content = `import { StrictMode } from 'react';
217
+ import { createRoot } from 'react-dom/client';
218
+ import { BrowserRouter } from "react-router-dom";
219
+ import { generateRoutes, useRoutes } from 'virtual:next-vite-router';
220
+
221
+ const routes = generateRoutes();
222
+
223
+ function App() {
224
+ const element = useRoutes(routes);
225
+ return element;
226
+ }
227
+
228
+ createRoot(document.getElementById('root')!).render(
229
+ <StrictMode>
230
+ <BrowserRouter>
231
+ <App />
232
+ </BrowserRouter>
233
+ </StrictMode>,
234
+ );
235
+ `;
236
+ fs.writeFileSync(mainPath, content, "utf-8");
237
+ }
238
+ function createGlobalsCss({ projectDir, src, tailwind }) {
239
+ const cssDir = src ? path.join(projectDir, "src") : projectDir;
240
+ const cssPath = path.join(cssDir, "globals.css");
241
+ if (!fs.existsSync(cssDir)) {
242
+ fs.mkdirSync(cssDir, { recursive: true });
243
+ }
244
+ let content;
245
+ if (tailwind) {
246
+ content = '@import "tailwindcss";\n';
247
+ } else {
248
+ content = `* {
249
+ margin: 0;
250
+ padding: 0;
251
+ box-sizing: border-box;
252
+ }
253
+
254
+ body {
255
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
256
+ "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
257
+ sans-serif;
258
+ -webkit-font-smoothing: antialiased;
259
+ -moz-osx-font-smoothing: grayscale;
260
+ }
261
+
262
+ html,
263
+ body,
264
+ #root {
265
+ width: 100%;
266
+ height: 100%;
267
+ }
268
+ `;
269
+ }
270
+ fs.writeFileSync(cssPath, content, "utf-8");
271
+ }
272
+ const layoutContentNoTailwind = `import { Outlet } from "react-router-dom";
273
+ import "@/globals.css";
274
+
275
+ export default function Layout() {
276
+ return (
277
+ <main>
278
+ <Outlet />
279
+ </main>
280
+ );
281
+ }
282
+ `;
283
+ const layoutContentTailwind = `import { Outlet } from "react-router-dom";
284
+ import "@/globals.css";
285
+
286
+ export default function Layout() {
287
+ return (
288
+ <main className="min-h-screen bg-background">
289
+ <Outlet />
290
+ </main>
291
+ );
292
+ }
293
+ `;
294
+ const pageContentNoTailwind = `export default function Page() {
295
+ return <h1>Welcome to the next-vite-router project!</h1>;
296
+ }
297
+ `;
298
+ const pageContentTailwind = `export default function Page() {
299
+ return <h1 className="text-2xl font-bold">Welcome to the next-vite-router project!</h1>;
300
+ }
301
+ `;
302
+ const examplePageContent = `export default function ExamplePage() {
303
+ return <h1>Welcome to the example page!</h1>;
304
+ }
305
+ `;
306
+ function createExampleStructure(projectDir, src, tailwindcss) {
307
+ const appDir = src ? path.join(projectDir, "src", "app") : path.join(projectDir, "app");
308
+ if (!fs.existsSync(appDir)) {
309
+ fs.mkdirSync(appDir, { recursive: true });
310
+ }
311
+ const layoutContent = tailwindcss ? layoutContentTailwind : layoutContentNoTailwind;
312
+ fs.writeFileSync(path.join(appDir, "layout.tsx"), layoutContent, "utf-8");
313
+ const pageContent = tailwindcss ? pageContentTailwind : pageContentNoTailwind;
314
+ fs.writeFileSync(path.join(appDir, "page.tsx"), pageContent, "utf-8");
315
+ const exampleDir = path.join(appDir, "example");
316
+ if (!fs.existsSync(exampleDir)) {
317
+ fs.mkdirSync(exampleDir, { recursive: true });
318
+ }
319
+ fs.writeFileSync(
320
+ path.join(exampleDir, "page.tsx"),
321
+ examplePageContent,
322
+ "utf-8"
323
+ );
324
+ }
325
+ function addTailwindToViteConfig(projectDir) {
326
+ const content = readViteConfig(projectDir);
327
+ if (!content) throw new Error("Vite config not found");
328
+ if (content.includes("@tailwindcss/vite")) {
329
+ return;
330
+ }
331
+ let updatedContent = content;
332
+ const importRegex = /(import\s+.*from\s+['"].*['"];?\s*\n)+/;
333
+ const match = updatedContent.match(importRegex);
334
+ if (match) {
335
+ const lastImportEnd = match[0].length;
336
+ updatedContent = updatedContent.slice(0, lastImportEnd) + "import tailwindcss from '@tailwindcss/vite';\n" + updatedContent.slice(lastImportEnd);
337
+ } else {
338
+ updatedContent = "import tailwindcss from '@tailwindcss/vite';\n\n" + updatedContent;
339
+ }
340
+ const pluginsArrayRegex = /plugins:\s*\[([^\]]*)\]/s;
341
+ const pluginsMatch = updatedContent.match(pluginsArrayRegex);
342
+ if (pluginsMatch) {
343
+ const pluginsContent = pluginsMatch[1];
344
+ const newPluginsContent = pluginsContent.trim() ? pluginsContent.trimEnd() + ",\n tailwindcss()" : "\n tailwindcss()\n ";
345
+ updatedContent = updatedContent.replace(
346
+ pluginsArrayRegex,
347
+ `plugins: [${newPluginsContent}
348
+ ]`
349
+ );
350
+ } else {
351
+ const defineConfigRegex = /defineConfig\(\{/;
352
+ updatedContent = updatedContent.replace(
353
+ defineConfigRegex,
354
+ "defineConfig({\n plugins: [tailwindcss()],"
355
+ );
356
+ }
357
+ writeViteConfig(projectDir, updatedContent);
358
+ }
359
+ const pm$1 = detectPackageManager();
360
+ function startNextViteRouterConfig({
361
+ projectDir = process.cwd(),
362
+ src,
363
+ tailwindcss
364
+ }) {
365
+ startViteConfig(projectDir, src);
366
+ const srcPath = path.join(projectDir, "src");
367
+ if (fs.existsSync(srcPath)) {
368
+ fs.rmSync(srcPath, { recursive: true, force: true });
369
+ }
370
+ updateTsConfigJson(projectDir, src);
371
+ updateAppTsConfig(projectDir, src);
372
+ createVirtualDTS(projectDir, src);
373
+ createMainTSX(projectDir, src);
374
+ if (tailwindcss) {
375
+ logger.info("Setting up Tailwind CSS...");
376
+ const addDevDepsCmd = pm$1.addDevDepsCommand([
377
+ "tailwindcss",
378
+ "@tailwindcss/vite"
379
+ ]);
380
+ child_process.execSync(addDevDepsCmd, { stdio: "inherit", cwd: projectDir });
381
+ addTailwindToViteConfig(projectDir);
382
+ }
383
+ createGlobalsCss({ projectDir, src, tailwind: tailwindcss });
384
+ createExampleStructure(projectDir, src, tailwindcss);
385
+ }
386
+ function startViteConfig(projectDir, src) {
387
+ const viteConfigPath = getViteConfigPath(projectDir);
388
+ if (!viteConfigPath) throw new Error("Vite config not found");
389
+ let viteConfigContent = readViteConfig(projectDir);
390
+ if (!viteConfigContent) throw new Error("Vite config empty");
391
+ if (!viteConfigContent.includes("import { resolve }")) {
392
+ viteConfigContent = `import { resolve } from "path";
393
+ ` + viteConfigContent;
394
+ }
395
+ if (!viteConfigContent.includes("import { nextViteRouter }")) {
396
+ viteConfigContent = `import { nextViteRouter } from "next-vite-router/plugin";
397
+ ` + viteConfigContent;
398
+ }
399
+ const resolveConfig = ` resolve: {
400
+ alias: {
401
+ "@": resolve(__dirname, "./${src ? "src" : "."}"),
402
+ },
403
+ },`;
404
+ const defineConfigRegex = /defineConfig\(\s*{/;
405
+ if (!viteConfigContent.includes("resolve:")) {
406
+ viteConfigContent = viteConfigContent.replace(
407
+ defineConfigRegex,
408
+ `defineConfig({
409
+ ${resolveConfig}
410
+ `
411
+ );
412
+ }
413
+ const pluginsRegex = /plugins\s*:\s*\[(.*?)\]/s;
414
+ const match = viteConfigContent.match(pluginsRegex);
415
+ const pluginString = `nextViteRouter({ pagesDir: "${src ? "src/app" : "app"}", pageFile: "page.tsx", layoutFile: "layout.tsx", notFoundFile: "not-found.tsx" })`;
416
+ if (match) {
417
+ const existing = match[1].trim();
418
+ const newPlugins = existing ? `${existing}, ${pluginString}` : pluginString;
419
+ viteConfigContent = viteConfigContent.replace(
420
+ pluginsRegex,
421
+ `plugins: [${newPlugins}]`
422
+ );
423
+ } else {
424
+ viteConfigContent = viteConfigContent.replace(
425
+ /defineConfig\(\s*{/,
426
+ `defineConfig({
427
+ plugins: [${pluginString}],`
428
+ );
429
+ }
430
+ writeViteConfig(projectDir, viteConfigContent);
431
+ }
432
+ const pm = detectPackageManager();
433
+ const init = new commander.Command().name("init").description(
434
+ "Initialize a new Vite project with next-vite-router configuration"
435
+ ).action(async () => {
436
+ const projectNameResponse = await prompts(
437
+ {
438
+ type: "text",
439
+ name: "projectName",
440
+ message: "Enter your project name:",
441
+ initial: "my-next-vite-router-app"
442
+ },
443
+ {
444
+ onCancel: () => {
445
+ logger.error("Project creation cancelled.");
446
+ process.exit(1);
447
+ }
448
+ }
449
+ );
450
+ const projectName = projectNameResponse.projectName;
451
+ const variantResponse = await prompts(
452
+ {
453
+ type: "select",
454
+ name: "template",
455
+ message: "Select a template:",
456
+ choices: [
457
+ { title: "React + TypeScript", value: "react-ts" },
458
+ {
459
+ title: "React + TypeScript (React Compiler)",
460
+ value: "react-compiler-ts"
461
+ },
462
+ { title: "React + SWC (Recommended)", value: "react-swc-ts" }
463
+ ],
464
+ initial: 0
465
+ },
466
+ {
467
+ onCancel: () => {
468
+ logger.error("Template selection cancelled.");
469
+ process.exit(1);
470
+ }
471
+ }
472
+ );
473
+ const variant = variantResponse.template;
474
+ const srcFolderResponse = await prompts(
475
+ {
476
+ type: "confirm",
477
+ name: "useSrc",
478
+ message: "Do you want to use a 'src' folder?",
479
+ initial: true
480
+ },
481
+ {
482
+ onCancel: () => {
483
+ logger.error("Src folder selection cancelled.");
484
+ process.exit(1);
485
+ }
486
+ }
487
+ );
488
+ const useSrc = srcFolderResponse.useSrc;
489
+ const tailwindResponse = await prompts(
490
+ {
491
+ type: "confirm",
492
+ name: "useTailwind",
493
+ message: "Do you want to set up Tailwind CSS?",
494
+ initial: true
495
+ },
496
+ {
497
+ onCancel: () => {
498
+ logger.error("Tailwind CSS setup cancelled.");
499
+ process.exit(1);
500
+ }
501
+ }
502
+ );
503
+ const useTailwind = tailwindResponse.useTailwind;
504
+ const createCommand = pm.createProjectCommand(projectName, variant);
505
+ logger.info(`Creating project "${projectName}" using ${pm.name}...`);
506
+ try {
507
+ child_process.execSync(createCommand, {
508
+ stdio: ["pipe", "inherit", "inherit"],
509
+ input: "n\n"
510
+ });
511
+ } catch (error) {
512
+ }
513
+ logger.info("Installing dependencies...");
514
+ child_process.execSync(pm.installCommand, { stdio: "inherit", cwd: projectName });
515
+ logger.info(
516
+ "Adding next-vite-router and react-router-dom as dependencies..."
517
+ );
518
+ const addDepsCmd = pm.addDepsCommand([
519
+ "next-vite-router",
520
+ "react-router-dom@latest"
521
+ ]);
522
+ child_process.execSync(addDepsCmd, { stdio: "inherit", cwd: projectName });
523
+ logger.info("Configuring next-vite-router in the project...");
524
+ startNextViteRouterConfig({
525
+ projectDir: `./${projectName}`,
526
+ src: useSrc,
527
+ tailwindcss: useTailwind
528
+ });
529
+ logger.success(`
530
+ Project "${projectName}" is ready!
531
+ `);
532
+ });
533
+ async function main() {
534
+ const program = new commander.Command();
535
+ program.name("next-vite-router").version("1.0.5").addCommand(init);
536
+ program.parse(process.argv);
537
+ }
538
+ main();
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "next-vite-router",
3
- "version": "1.0.4",
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",
7
7
  "types": "./dist/index.d.ts",
8
+ "bin": {
9
+ "next-vite-router": "./dist/cli.cjs"
10
+ },
8
11
  "exports": {
9
12
  ".": {
10
13
  "import": "./dist/index.js",
@@ -44,16 +47,23 @@
44
47
  },
45
48
  "devDependencies": {
46
49
  "@types/node": "^24.10.1",
50
+ "@types/prompts": "^2.4.9",
47
51
  "@types/react": "^18.0.0",
48
52
  "@types/react-dom": "^18.0.0",
49
53
  "typescript": "^5.0.0",
50
54
  "vite": "^5.0.0",
51
55
  "vite-plugin-dts": "^3.0.0"
52
56
  },
57
+ "dependencies": {
58
+ "commander": "^14.0.2",
59
+ "kleur": "^4.1.5",
60
+ "prompts": "^2.4.2"
61
+ },
53
62
  "scripts": {
54
63
  "dev": "vite build --watch",
55
- "build": "vite build",
64
+ "build": "vite build && vite build -c vite.config.cli.ts",
56
65
  "test:local": "node test/test-package.js",
57
- "preview": "pnpm pack --dry-run"
66
+ "preview": "pnpm pack --dry-run",
67
+ "cli": "cd test && node ../dist/cli.cjs init"
58
68
  }
59
69
  }