ts-file-router 6.0.1 → 6.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,19 +1,20 @@
1
1
  # ðŸ“Ķ ts-file-router
2
2
 
3
- A lightweight TypeScript filesystem router generator.
4
- Automatically scans folders and outputs a clean, structured `routes.ts` tree ready for dynamic imports (e.g., `React.lazy`).
3
+ A lightweight **filesystem router generator** for TypeScript projects. Automatically scans your folder structure and generates a clean, typed `routes.ts` tree ready for dynamic imports (e.g., `React.lazy`).
5
4
 
6
5
  ---
7
6
 
8
7
  ## âœĻ Features
9
8
 
10
- - 🔍 Recursive folder scanning
11
- - 📄 Auto-generated `routes.ts` (TypeScript code, no `resolveJsonModule` required)
12
- - ⚛ïļ Works perfectly with `React.lazy()` and dynamic imports
13
- - 📘 Full TypeScript `.d.ts` definitions included
14
- - ðŸ§Đ Custom route file name (default: `page.ts`)
15
- - ðŸŠķ Zero runtime dependencies
16
- - ðŸŽŊ Clean, formatted output with readable keys
9
+ - 🔍 **Automatic folder scanning** - Recursively scans your pages/screens directory
10
+ - 📄 **Generated TypeScript routes** - Fully typed `routes.ts` file with `as const` assertions
11
+ - ⚛ïļ **Framework agnostic** - Works with React.lazy, Vue, Solid, or any framework with dynamic imports
12
+ - ðŸŠķ **Zero runtime dependencies** - Only used at build/dev time
13
+ - 🔄 **File watcher support** - Auto-regenerate routes when files change (powered by Chokidar)
14
+ - ðŸŽĻ **Biome formatting** - Output files are automatically formatted with Biome
15
+ - ðŸ§Đ **Vite plugin** - Seamless integration with Vite dev server
16
+ - ðŸšŦ **Smart file filtering** - Ignores `index` files, `_` prefixed files (private routes), and output files
17
+ - 📘 **Full TypeScript support** - Complete `.d.ts` definitions included
17
18
 
18
19
  ---
19
20
 
@@ -21,16 +22,24 @@ Automatically scans folders and outputs a clean, structured `routes.ts` tree rea
21
22
 
22
23
  ```bash
23
24
  npm install ts-file-router
24
- # or
25
- yarn add ts-file-router
25
+ ```
26
+
27
+ **Optional dependencies:**
28
+
29
+ ```bash
30
+ # For file watcher support
31
+ npm install chokidar
26
32
 
33
+ # Vite is automatically supported as a peer dependency
27
34
  ```
28
35
 
29
36
  ---
30
37
 
31
- ## ðŸŽŊ Usage
38
+ ## 🚀 Quick Start
39
+
40
+ ### 1. Basic Usage (One-time generation)
32
41
 
33
- Create a script to generate your routes. Example:
42
+ Create a script to generate your routes:
34
43
 
35
44
  ```js
36
45
  // scripts/generate-routes.mjs
@@ -38,68 +47,239 @@ import { generateRoutes } from 'ts-file-router';
38
47
 
39
48
  generateRoutes({
40
49
  baseFolder: 'src/screens',
41
- outputFile: 'src/screens/routes.ts',
50
+ outputFile: 'routes.ts',
42
51
  });
43
52
  ```
44
53
 
45
- ## ðŸŽŊ Usage With Vite
54
+ Run it:
55
+
56
+ ```bash
57
+ node scripts/generate-routes.mjs
58
+ ```
46
59
 
47
- Create a script to generate your routes. Example:
60
+ ### 2. With File Watcher (Auto-regenerate on changes)
48
61
 
49
62
  ```js
50
- // scripts/vite.config.ts
63
+ // scripts/generate-routes.mjs
64
+ import { generateRoutes } from 'ts-file-router';
65
+
66
+ generateRoutes({
67
+ baseFolder: 'src/screens',
68
+ outputFile: 'routes.ts',
69
+ options: {
70
+ watcher: {
71
+ watch: true,
72
+ debounce: 500, // Wait 500ms after changes before regenerating
73
+ },
74
+ exitCodeOnResolution: false, // Don't exit process after generation
75
+ },
76
+ });
77
+ ```
78
+
79
+ This will keep running and regenerate routes whenever you add, remove, or modify files in the `src/screens` folder.
80
+
81
+ ### 3. With Vite Plugin
82
+
83
+ ```ts
84
+ // vite.config.ts
85
+ import { defineConfig } from 'vite';
51
86
  import { generateRoutesPlugin } from 'ts-file-router';
52
87
 
53
- // https://vite.dev/config/
54
88
  export default defineConfig({
55
89
  plugins: [
56
90
  generateRoutesPlugin({
57
91
  baseFolder: 'src/screens',
58
- outputFile: 'screens.ts',
92
+ outputFile: 'src/screens/routes.ts',
93
+ // Optional: customize watcher behavior
94
+ options: {
95
+ watcher: { watch: true, debounce: 500 },
96
+ exitCodeOnResolution: false,
97
+ },
59
98
  }),
60
99
  ],
61
100
  });
62
101
  ```
63
102
 
64
- ## ðŸŽŊ Usage With Watcher (Chokidar Peer Dependencie)
103
+ The plugin automatically runs during Vite's dev server (`vite dev`) and regenerates routes on file changes.
104
+
105
+ ---
65
106
 
66
- Create a script to generate your routes. Example:
107
+ ## 📂 How It Works
67
108
 
68
- ```js
69
- // scripts/generate-routes.mjs
70
- import { generateRoutes } from 'ts-file-router';
109
+ Given this folder structure:
71
110
 
72
- generateRoutes({
73
- baseFolder: 'src/screens',
74
- outputFile: 'screens.ts',
75
- options: {
76
- watcher: { watch: true, debounce: 500 },
77
- exitCodeOnResolution: false,
111
+ ```
112
+ src/screens/ # Home page
113
+ ├── about/
114
+ │ └── page.tsx # About page
115
+ ├── users/
116
+ │ ├── page.tsx # Users list
117
+ │ ├── profile/
118
+ │ │ └── page.tsx # User profile
119
+ │ └── _private/
120
+ │ └── page.tsx # Ignored (starts with _)
121
+ └── index.tsx # Ignored (index file)
122
+ ```
123
+
124
+ Generates:
125
+
126
+ ```ts
127
+ // GENERATED WITH TS-FILE-ROUTER DO NOT EDIT
128
+ export const routes = {
129
+ about: {
130
+ path: '/about',
131
+ import: () => import('./about/page'),
78
132
  },
79
- });
133
+ users: {
134
+ page: {
135
+ path: '/users',
136
+ import: () => import('./users/page'),
137
+ },
138
+ profile: {
139
+ path: '/users/profile',
140
+ import: () => import('./users/profile/page'),
141
+ },
142
+ },
143
+ } as const;
80
144
  ```
81
145
 
82
- ## What this does
146
+ ---
83
147
 
84
- - baseFolder: Root directory where your screens/pages live
148
+ ## 🔧 Configuration Options
85
149
 
86
- - routeFileName: File that represents a route (e.g. page.tsx)
150
+ ### `generateRoutes()` Parameters
87
151
 
88
- - outputFile: Generated routes file (fully typed)
152
+ | Parameter | Type | Required | Description |
153
+ | ------------ | ------------------------ | -------- | ---------------------------------- |
154
+ | `baseFolder` | `string` | ✅ Yes | Root directory to scan for routes |
155
+ | `outputFile` | `string` | ✅ Yes | Path for the generated routes file |
156
+ | `options` | `TGenerateRoutesOptions` | ❌ No | Additional configuration |
89
157
 
90
- Run the script with:
158
+ ### Options Object
91
159
 
92
- node scripts/generate-routes.mjs
160
+ ```ts
161
+ interface TGenerateRoutesOptions {
162
+ watcher?: {
163
+ watch: boolean; // Enable file watching
164
+ debounce?: number; // Debounce delay in ms (default: 500)
165
+ };
166
+ exitCodeOnResolution?: boolean; // Exit process after generation (default: true)
167
+ }
168
+ ```
93
169
 
94
- or setup generateRoutesPlugin in vite.config.ts
170
+ ### `exitCodeOnResolution`
95
171
 
96
- ## Output based on your folder
172
+ - **`true`** (default for CLI): Process exits with code `0` on success or `1` on error
173
+ - **`false`** (default for Vite/plugin): Process keeps running (required for watchers)
97
174
 
98
- ```ts
99
- export const routes = {
100
- page: {
101
- path: '/',
102
- import: import('./page'),
103
- },
104
- } as const;
175
+ ---
176
+
177
+ ## ðŸŽŊ Usage Examples
178
+
179
+ ### With React Router And React Lazy Using
180
+
181
+ ```tsx
182
+ import { routes } from './screens/routes';
183
+ import { BrowserRouter, Routes, Route } from 'react-router-dom';
184
+ import React from 'react';
185
+
186
+ const About = lazy(() =>
187
+ routes.about.import().then((r) => ({ default: res.About })),
188
+ );
189
+
190
+ const Profile = lazy(() =>
191
+ routes.users.profile.import().then((r) => ({ default: res.Profile })),
192
+ );
193
+
194
+ function App() {
195
+ return (
196
+ <BrowserRouter>
197
+ <Routes>
198
+ <Route path={routes.about.path} element={<About />} />
199
+ <Route path={routes.users.profile.path} element={<Profile />} />
200
+ </Routes>
201
+ </BrowserRouter>
202
+ );
203
+ }
204
+ ```
205
+
206
+ ---
207
+
208
+ ## ðŸšŦ File Filtering Rules
209
+
210
+ The following files/folders are **automatically ignored**:
211
+
212
+ - **`index.*`** files - Index files are skipped
213
+ - **`_` prefixed** files/folders - Files starting with underscore are treated as private
214
+ - **Output file** - The generated routes file is ignored to prevent infinite loops
215
+
216
+ This allows you to have helper files, components, or private routes alongside your page files without polluting the routes tree.
217
+
218
+ ---
219
+
220
+ ## ðŸ“Ķ Output File Structure
221
+
222
+ The generated file is a TypeScript module with:
223
+
224
+ - ✅ `export const routes` - Named export with all routes
225
+ - ✅ `as const` assertion - Full type inference for route paths and imports
226
+
227
+ ## 🛠 Advanced Usage
228
+
229
+ ### Custom Route File Names
230
+
231
+ By default, any file (except ignored ones) becomes a route. You can control this by:
232
+
233
+ 1. Using a consistent naming convention (e.g., all pages named `page.tsx`)
234
+ 2. Using `_` prefix for non-route files: `_components.tsx`, `_utils.ts`
235
+
236
+ ### Watcher Events
237
+
238
+ When using the watcher, routes regenerate on:
239
+
240
+ - `add` - New file added
241
+ - `addDir` - New directory added
242
+ - `change` - File modified
243
+ - `unlink` - File deleted
244
+ - `unlinkDir` - Directory deleted
245
+
246
+ If the output file is deleted, it's automatically regenerated.
247
+
248
+ ### Graceful Shutdown
249
+
250
+ The watcher listens for:
251
+
252
+ - `SIGINT` (Ctrl+C) - Graceful cleanup
253
+ - `SIGTERM` - Container/process termination
254
+
255
+ Both trigger proper watcher cleanup before exit.
256
+
257
+ ---
258
+
259
+ ## 📝 Tips
260
+
261
+ 1. **Add to `package.json`**:
262
+
263
+ ```json
264
+ {
265
+ "scripts": {
266
+ "generate:routes": "node scripts/generate-routes.mjs",
267
+ "dev": "npm run generate:routes && vite",
268
+ "dev:watch": "node scripts/generate-routes.mjs --watch"
269
+ }
270
+ }
105
271
  ```
272
+
273
+ 2. **Use relative paths in output**: The `outputFile` path is relative to `baseFolder`.
274
+
275
+ ---
276
+
277
+ ## ðŸĪ Contributing
278
+
279
+ Found a bug or have a feature request? Open an issue or submit a PR!
280
+
281
+ ---
282
+
283
+ ## 📄 License
284
+
285
+ ISC ÂĐ MatheusF10
@@ -1 +1 @@
1
- {"version":3,"file":"serializeHelper.d.ts","sourceRoot":"","sources":["../../src/helpers/serializeHelper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAmJtD,eAAO,MAAM,eAAe;kCAjHA,OAAO,KAAG,KAAK,IAAI,UAAU;2CAkGd,WAAW,cAAc,MAAM;kDAhBxB,MAAM,QAAQ,MAAM;CAmC5D,CAAC"}
1
+ {"version":3,"file":"serializeHelper.d.ts","sourceRoot":"","sources":["../../src/helpers/serializeHelper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AA0JtD,eAAO,MAAM,eAAe;kCAxHA,OAAO,KAAG,KAAK,IAAI,UAAU;2CAyGd,WAAW,cAAc,MAAM;kDAhBxB,MAAM,QAAQ,MAAM;CAmC5D,CAAC"}
@@ -36,7 +36,12 @@ const createRouteObject = (obj) => {
36
36
  if (isRouteLeaf(value)) {
37
37
  return ts.factory.createPropertyAssignment(ts.factory.createIdentifier(key), ts.factory.createObjectLiteralExpression([
38
38
  ts.factory.createPropertyAssignment('path', ts.factory.createStringLiteral(value.path)),
39
- ts.factory.createPropertyAssignment('import', ts.factory.createCallExpression(ts.factory.createIdentifier('import'), undefined, [ts.factory.createStringLiteral(value.import)])),
39
+ ts.factory.createPropertyAssignment('import', ts.factory.createArrowFunction(undefined, // modifiers
40
+ undefined, // type parameters
41
+ [], // parameters
42
+ undefined, // return type
43
+ ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), // =>
44
+ ts.factory.createCallExpression(ts.factory.createIdentifier('import'), undefined, [ts.factory.createStringLiteral(value.import)]))),
40
45
  ], true));
41
46
  }
42
47
  // Recursive object
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ts-file-router",
3
- "version": "6.0.1",
3
+ "version": "6.0.2",
4
4
  "description": "router based on project files using typescript",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",