Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/node-ecosystem/vite-plugin-build-routes
Vite Plugin to build API routes
https://github.com/node-ecosystem/vite-plugin-build-routes
api api-rest api-routes build plugin routes routing vite
Last synced: 2 days ago
JSON representation
Vite Plugin to build API routes
- Host: GitHub
- URL: https://github.com/node-ecosystem/vite-plugin-build-routes
- Owner: node-ecosystem
- License: other
- Created: 2024-12-23T15:11:31.000Z (13 days ago)
- Default Branch: master
- Last Pushed: 2024-12-27T14:33:57.000Z (9 days ago)
- Last Synced: 2024-12-28T09:10:28.668Z (9 days ago)
- Topics: api, api-rest, api-routes, build, plugin, routes, routing, vite
- Language: TypeScript
- Homepage:
- Size: 1020 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# vite-plugin-build-routes
A Vite plugin to simplify the build of API routes: copy all files from a _target_ directory to a _build_ output directory.
## ⚙️ Install
```sh
yarn add -D vite-plugin-build-routes
```## 📖 Usage
Example:
- `/server/api` as _target_ directory that contains `/server/api/user/index.ts` file
- `/dist` as _build_ output directory
- register `vite-plugin-build-routes` plugin and server plugin (see below)
- build with Vite (e.g. `yarn vite build`)
- the _result_ is `/dist/server/api/user/index.mjs`### Register the Vite Plugin (example with [Vike](https://vike.dev))
```ts
// vite.config.ts
import vike from 'vike/plugin'
import { vikeNode } from 'vike-node/plugin'
import type { UserConfig } from 'vite'
import viteBuildRoutes from 'vite-plugin-build-routes'export default {
plugins: [
vike(),
vikeNode('server/index.ts'),
viteBuildRoutes('server/api')
// OR use a pattern instead of default '**/*.ts'
// viteBuildRoutes({
// entry: 'server/api',
// pattern: '**/*.js'
// })
]
} satisfies UserConfig
```### Use the Server Plugin (example with [Hono](https://hono.dev))
Use the [universal-autorouter](https://github.com/node-ecosystem/universal-autorouter) package to automatically scan and load all routes to the server.
```ts
// /server/index.ts
import path from 'node:path'
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import vike from 'vike-node/hono'
import autoloadRoutes from 'universal-autorouter'const app = await autoloadRoutes(new Hono(), {
pattern: process.env.NODE_ENV === 'production' ? '**/*.mjs' : '**/*.ts',
prefix: '/api',
routesDir: path.resolve(import.meta.dirname, 'api'),
viteDevServer: globalThis.__vikeNode?.viteDevServer // needed for Vite's HMR
})app.use(vike())
const port = +(process.env.PORT || 3000)
serve({
fetch: app.fetch,
port
}, () => console.log(`Server running at http://localhost:${port}`))
```