Top Related Projects
🚦 The official router for Vue 2
The Intuitive Vue Framework.
Declarative routing for React
Quick Overview
Unplugin-vue-router is a file-based routing plugin for Vue.js applications. It automatically generates routes based on your file structure, providing a seamless and efficient way to handle routing in Vue projects. The plugin is designed to work with both Vue 2 and Vue 3, offering flexibility and ease of use.
Pros
- Automatic route generation based on file structure, reducing manual configuration
- TypeScript support with auto-completion and type checking for routes
- Supports both Vue 2 and Vue 3 projects
- Integrates well with various build tools (Vite, Webpack, Rollup, esbuild)
Cons
- May require adjustments to existing project structures for optimal use
- Learning curve for developers accustomed to manual route configuration
- Limited customization options compared to manually defined routes
- Potential performance impact for very large applications with many routes
Code Examples
- Basic route definition:
<!-- src/pages/index.vue -->
<template>
<h1>Welcome to the home page</h1>
</template>
This file automatically creates a route for the home page ("/").
- Dynamic route parameters:
<!-- src/pages/users/[id].vue -->
<template>
<div>User profile for ID: {{ $route.params.id }}</div>
</template>
This creates a dynamic route for user profiles ("/users/:id").
- Nested routes:
<!-- src/pages/blog/[slug].vue -->
<template>
<div>
<h1>{{ post.title }}</h1>
<router-view></router-view>
</div>
</template>
This creates a nested route structure for blog posts with potential child routes.
Getting Started
-
Install the plugin:
npm install -D unplugin-vue-router
-
Add the plugin to your Vite config:
// vite.config.js import { defineConfig } from 'vite' import VueRouter from 'unplugin-vue-router/vite' export default defineConfig({ plugins: [ VueRouter({ /* options */ }), ], })
-
Update your main.js file:
import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router/auto' import App from './App.vue' const router = createRouter({ history: createWebHistory(), }) createApp(App).use(router).mount('#app')
-
Start creating your page components in the
src/pages
directory, and the plugin will automatically generate routes based on your file structure.
Competitor Comparisons
🚦 The official router for Vue 2
Pros of vue-router
- Well-established and widely adopted in the Vue.js ecosystem
- Extensive documentation and community support
- Seamless integration with Vue.js core and other official libraries
Cons of vue-router
- Requires manual route configuration, which can be tedious for large applications
- Less type-safe compared to unplugin-vue-router
- May lead to more boilerplate code for complex routing scenarios
Code Comparison
vue-router:
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/user/:id', component: User }
]
const router = createRouter({
history: createWebHistory(),
routes
})
unplugin-vue-router:
// Routes are automatically generated based on file structure
import { createRouter, createWebHistory } from 'vue-router/auto'
const router = createRouter({
history: createWebHistory(),
})
Key Differences
- unplugin-vue-router generates routes automatically based on file structure, reducing manual configuration
- unplugin-vue-router provides better TypeScript support and type safety
- vue-router offers more flexibility in route configuration, while unplugin-vue-router follows a more opinionated approach
Conclusion
While vue-router remains a solid choice for many Vue.js projects, unplugin-vue-router offers advantages in terms of automatic route generation and improved type safety. The choice between the two depends on project requirements and developer preferences.
Pros of reach/router
- Designed for React applications, providing seamless integration with React components
- Offers accessibility features out of the box, enhancing user experience for all users
- Supports relative routing, making it easier to create nested routes and reusable components
Cons of reach/router
- Limited to React applications, not suitable for Vue.js projects
- May require more manual configuration compared to unplugin-vue-router's automatic route generation
- Less active development and community support compared to newer routing solutions
Code Comparison
reach/router:
import { Router, Link } from "@reach/router"
const App = () => (
<Router>
<Home path="/" />
<Dashboard path="dashboard" />
</Router>
)
unplugin-vue-router:
<template>
<RouterView />
</template>
<script setup>
import { RouterView } from 'vue-router'
</script>
unplugin-vue-router automatically generates routes based on file structure, reducing the need for manual route configuration. reach/router requires explicit route definitions within the Router component. While reach/router offers a more React-centric approach with built-in accessibility features, unplugin-vue-router provides a more streamlined experience for Vue.js developers with its automatic route generation and integration with the Vue ecosystem.
The Intuitive Vue Framework.
Pros of Nuxt
- Full-featured framework with built-in SSR, routing, and state management
- Extensive ecosystem with official modules and community plugins
- Automatic code splitting and optimized performance out of the box
Cons of Nuxt
- Steeper learning curve due to its comprehensive nature
- Less flexibility in customizing the routing system
- Potentially heavier bundle size for simpler applications
Code Comparison
unplugin-vue-router:
import { createRouter, createWebHistory } from 'vue-router/auto'
const router = createRouter({
history: createWebHistory(),
})
Nuxt:
// No explicit router configuration needed
// Routes are automatically generated based on the file structure
// in the `pages` directory
Key Differences
- unplugin-vue-router focuses solely on file-based routing for Vue.js applications
- Nuxt is a complete framework that includes routing along with many other features
- unplugin-vue-router offers more granular control over route generation
- Nuxt provides a more opinionated structure and development workflow
Use Cases
- Choose unplugin-vue-router for existing Vue.js projects or when you need fine-grained routing control
- Opt for Nuxt when building full-stack applications or when you want a comprehensive, batteries-included framework
Declarative routing for React
Pros of React Router
- Mature and widely adopted in the React ecosystem
- Extensive documentation and community support
- Supports nested routing and dynamic route matching
Cons of React Router
- More complex API compared to Vue Router
- Requires more boilerplate code for basic routing setups
- Less integration with build tools for automatic route generation
Code Comparison
React Router:
import { BrowserRouter, Route, Switch } from 'react-router-dom';
<BrowserRouter>
<Switch>
<Route path="/about" component={About} />
<Route path="/" exact component={Home} />
</Switch>
</BrowserRouter>
unplugin-vue-router:
<template>
<RouterView />
</template>
<script setup>
import { RouterView } from 'vue-router'
</script>
Key Differences
- unplugin-vue-router automatically generates routes based on file structure, reducing manual configuration
- React Router requires explicit route definitions, offering more control but increased verbosity
- unplugin-vue-router integrates seamlessly with Vue's Single File Component structure
- React Router provides a more flexible routing system, allowing for complex nested routes and route-based code splitting
Conclusion
While React Router offers a robust and flexible routing solution for React applications, unplugin-vue-router provides a more streamlined and automated approach for Vue projects. The choice between the two depends on the specific framework and development preferences of the project.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
unplugin-vue-router
Automatic file based Routing in Vue with TS support â¨
This build-time plugin simplifies your routing setup and makes it safer and easier to use thanks to TypeScript. Requires Vue Router >=4.4.0.
[!WARNING] While unplugin-vue-router typed routing and file based routing is fundamentally stable, it contains other experimental APIs that are subject to change (e.g. Data Loaders). Make sure to check the relevant Documentation for the latest information. If you find any issue, design flaw, or have ideas to improve it, please, open open an issue or a Discussion.
Install
npm i -D unplugin-vue-router
Add VueRouter plugin before Vue plugin:
Vite
// vite.config.ts
import VueRouter from 'unplugin-vue-router/vite'
export default defineConfig({
plugins: [
VueRouter({
/* options */
}),
// â ï¸ Vue must be placed after VueRouter()
Vue(),
],
})
Example: playground/
Rollup
// rollup.config.js
import VueRouter from 'unplugin-vue-router/rollup'
export default {
plugins: [
VueRouter({
/* options */
}),
// â ï¸ Vue must be placed after VueRouter()
Vue(),
],
}
Webpack
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-router/webpack')({
/* options */
}),
],
}
Vue CLI
// vue.config.js
module.exports = {
configureWebpack: {
plugins: [
require('unplugin-vue-router/webpack')({
/* options */
}),
],
},
}
esbuild
// esbuild.config.js
import { build } from 'esbuild'
import VueRouter from 'unplugin-vue-router/esbuild'
build({
plugins: [VueRouter()],
})
Setup
After installing, you should run your dev server (usually npm run dev
) to generate the first version of the types. Then you need to add the types to your tsconfig.json
.
{
"include": [
// ...
"./typed-router.d.ts"
],
// ...
"compilerOptions": {
// ...
"moduleResolution": "Bundler"
// ...
}
}
Then, if you have an env.d.ts
file like the one created by npm vue create <my-project>
, add the unplugin-vue-router/client
types to it:
// env.d.ts
/// <reference types="vite/client" />
/// <reference types="unplugin-vue-router/client" />
If you don't have an env.d.ts
file, you can create one and add the unplugin-vue-router types to it or you can add them to the types
property in your tsconfig.json
:
{
"compilerOptions": {
// ...
"types": ["unplugin-vue-router/client"]
}
}
Finally, import the generated routes from vue-router/auto-routes
and pass them to the router:
import { createRouter, createWebHistory } from 'vue-router'
+import { routes } from 'vue-router/auto-routes'
createRouter({
history: createWebHistory(),
// pass the generated routes written by the plugin ð¤
+ routes,
})
Alternatively, you can also import the routes
array and create the router manually or pass it to some plugin. Here is an example with Vitesse starter:
import { ViteSSG } from 'vite-ssg'
import { setupLayouts } from 'virtual:generated-layouts'
import App from './App.vue'
import type { UserModule } from './types'
-import generatedRoutes from '~pages'
+import { routes } from 'vue-router/auto-routes'
import '@unocss/reset/tailwind.css'
import './styles/main.css'
import 'uno.css'
-const routes = setupLayouts(generatedRoutes)
// https://github.com/antfu/vite-ssg
export const createApp = ViteSSG(
App,
{
- routes,
+ routes: setupLayouts(routes),
base: import.meta.env.BASE_URL
},
(ctx) => {
// install all modules under `modules/`
Object.values(import.meta.glob<{ install: UserModule }>('./modules/*.ts', { eager: true }))
.forEach(i => i.install?.(ctx))
},
)
License
Top Related Projects
🚦 The official router for Vue 2
The Intuitive Vue Framework.
Declarative routing for React
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot