Getting Started
This guide will walk you through the process of setting up the vite-plugin-remix-routes
plugin in your Vite project. You can start with a new project or add the plugin to an existing project.
Step 1: Installation
First, install vite-plugin-remix-routes
and react-router-dom
packages:
npm install --save-dev vite-plugin-remix-routes react-router-dom
Then, add the plugin to your vite.config.ts
:
import { defineConfig } from 'vite'
import { remixFlatRoutes } from 'vite-plugin-remix-flat-routes'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [remixFlatRoutes(
// plugin options
)],
})
Step 2: Define your first route
Create a hello.tsx
file in the app/routes
directory with the following contents. This directory contains all your application routes, and you can change it in the plugin's configuration options.
mkdir app/routes && touch app/routes/hello.tsx
Choose route load strategy
In order to keep your application bundles small and support code-splitting of your routes, you can define lazy routes. default export
of the route file is a lazy-loaded route
// app/routes/hello.tsx
export default function Hello() {
return (
<div>
<h1>Hello World!</h1>
<p>Powered by Vite, React, and vite-plugin-remix-flat-routes</p>
</div>
)
}
If you want to define a non-lazy-loaded route, you can use named Component
exports:
// app/routes/hello.tsx
export function Component() {
// return ...
}
Step 3: Create Router
Create routes using react-router-dom Router component.
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import { createRoot } from 'react-dom/client'
import { routes } from 'virtual:remix-flat-routes'
createRoot(document.querySelector('#root')!).render(
<RouterProvider router={createBrowserRouter(routes)} />,
)
The virtual:remix-flat-routes
export is generated by the vite-plugin-remix-routes
and contains all the routes defined in your app/routes
.
To use the data APIs in react-router^6.4.0
, you should use the createBrowserRouter
to create a router instance. Check out the Picking a Router guide in React Router documentation to learn more.
If you are using typescript, add the following to your tsconfig.json
:
{
"compilerOptions": {
"types": ["vite-plugin-remix-flat-routes/virtual"]
}
}
Step 4: Add React-fast-refresh support
Install @vitejs/plugin-react>=4.3.2
or @vitejs/plugin-react-swc >= 3.6.0
Then add the plugin to your vite.config.ts
:
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import { remixFlatRoutes } from 'vite-plugin-remix-flat-routes'
export default defineConfig({
plugins: [
react(),
remixFlatRoutes(
// plugin options
)],
})
What's next?
By now, you should be able to install the vite-plugin-remix-routes
plugin and create a new route. Next, we'll learn how to define application routes.
You can also check the config reference for customizing the plugin's behavior.