4.4 KiB
Vite Plugin: File-based Routing
The sigproRouter plugin for Vite automates route generation by scanning your pages directory. It creates a virtual module that you can import directly into your code, eliminating the need to maintain a manual routes array.
1. Project Structure
To use the plugin, organize your files within the src/pages directory. The folder hierarchy directly determines your application's URL structure. SigPro uses brackets [param] for dynamic segments.
my-sigpro-app/
├── src/
│ ├── pages/
│ │ ├── index.js → #/
│ │ ├── about.js → #/about
│ │ ├── users/
│ │ │ └── [id].js → #/users/:id
│ │ └── blog/
│ │ ├── index.js → #/blog
│ │ └── [slug].js → #/blog/:slug
│ ├── App.js (Main Layout)
│ └── main.js (Entry Point)
├── vite.config.js
└── package.json
2. Setup & Configuration
Add the plugin to your vite.config.js. It works out of the box with zero configuration.
// vite.config.js
import { defineConfig } from 'vite';
import { sigproRouter } from 'sigpro/vite';
export default defineConfig({
plugins: [sigproRouter()]
});
3. Implementation
Thanks to SigPro's synchronous initialization, you no longer need to wrap your mounting logic in .then() blocks.
// src/main.js
import SigPro from 'sigpro';
import { routes } from 'virtual:sigpro-routes';
// The Core already has Router ready
Mount(Router(routes), '#app');
// src/App.js
import { routes } from 'virtual:sigpro-routes';
export default () => div({ class: 'layout' }, [
header([
h1("SigPro App"),
nav([
button({ onclick: () => Router.go('/') }, "Home"),
button({ onclick: () => Router.go('/blog') }, "Blog")
])
]),
// Only the content inside <main> will be swapped reactively
main(Router(routes))
]);
4. Route Mapping Reference
The plugin follows a simple convention to transform your file system into a routing map.
| File Path | Generated Path | Description |
|---|---|---|
index.js |
/ | The application root. |
about.js |
/about | A static page. |
[id].js |
/:id | Dynamic parameter (passed to the component). |
blog/index.js |
/blog | Folder index page. |
_utils.js |
Ignored | Files starting with _ are excluded from routing. |
5. How it Works (Vite Virtual Module)
The plugin generates a virtual module named virtual:sigpro-routes. This module exports an array of objects compatible with Router():
// Internal representation generated by the plugin
export const routes = [
{ path: '/', component: () => import('/src/pages/index.js') },
{ path: '/users/:id', component: () => import('/src/pages/users/[id].js') },
// ...
];
Because it uses dynamic import(), Vite automatically performs Code Splitting, meaning each page is its own small JS file that only loads when the user navigates to it.