Tired of manually configuring routes in your Vue.js application? As your project scales, managing routes in a separate JavaScript file can quickly become cumbersome and error-prone as your application grows.
Luckily, there's a better way! This article introduces you to the exciting world of Automatic File-Based Routing in Vue.js using unplugin-vue-router
. Say goodbye to verbose router configuration files and embrace a more intuitive, maintainable, and developer-friendly way to define your application's routes.
unplugin-vue-router is a Vue.js build-time plugin that enables Automatic File-Based Routing with type-safe precision. This innovative approach leverages the power of Typescript to streamline your routing setup.
💡 Heads up! If you prefer video learning we have an entire course dedicated to
unplugin-vue-router
. Watch the Enhanced Routing with UnPlugin Vue Router course now!
The plugin was created by Eduardo San Martin, the mastermind behind Pinia (Vue’s official state management solution) and Vue Router (Vue’s official routing engine). He built this tool after trying to type the router directly in Vue Router using Typescript, which wasn’t as fast and pleasant to use as he thought it would be. This is why he decided to craft a build-based tool that handles the task at build time.
unplugin-vue-router
helps eliminating the need for manual route configuration, improving code maintainability and the developer experience. With this plugin, your routes are automatically inferred from the file structure of your application's src/pages
directory.
Have you explored Nuxt Pages yet? If so, you've probably enjoyed the ease of not having to handle your routing system manually. Thanks to Eduardo, now we can bring that same convenience to standalone Vue.js apps, along with a bunch of extra features to boot.
Let’s go through some of the advantages of using automatic file-based routing with unplugin-vue-router
:
unplugin-vue-router
automatically generates routes based on the file structure, saving time and effort.src/pages
directory. This structure aligns perfectly with automatic file-based routing, promoting a clean and organized codebase.unplugin-vue-router
provides excellent support for TypeScript, ensuring type safety in your route definitions. Enjoy detecting invalid routes in real-time and autocompletion for links.unplugin-vue-router
uses lazy loading for routes. This means only the components needed for the current route are loaded, improving initial page load times and overall application performance.Finally, It’s worth mentioning that we can now use unplugin-vue-rotuter
in your Nuxt 3 app by enabling an experimental property called typedPages.
Let's dive into how to set up and use unplugin-vue-router
in a Vue.js 3 Vite project with TypeScript support.
The first thing we need to do is to install the package via npm or your preferred package manage:
npm i -D unplugin-vue-router
This isntalled version 0.9.0
of the package. Then, head to vite.config.ts
and make sure import the Vue Router plugin from unplugin-vue-router/vite
and add it before Vue
plugin.
// vite.config.ts
import VueRouter from 'unplugin-vue-router/vite'
export default defineConfig({
plugins: [
VueRouter({}),
Vue(),
],
})
The next step will be to generate the first version of the types and import it to tsconfig.json
{
"include": [
// ...
"./typed-router.d.ts"
],
"compilerOptions": {
// ...
"types": ["unplugin-vue-router/client"]
}
}
Finally, head to the file where the Vue Router instance is being created, and change the imports from vue-router
to vue-router/auto
. In addition, import routes
from vue-router/auto-routes
to automatically pass the generated routes to Vue Router.
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router/auto'
import { routes } from 'vue-router/auto-routes'
import App from './App.vue'
const router = createRouter({
history: createWebHistory(),
routes
})
createApp(App)
.use(router)
.mount('#app')
And voila, you're now set to say goodbye to the tedious task of manually registering your application's routes.
Now, you can create src/pages
directory, and all your Vue components in there, will automatically become routes and pages. Yet, to ensure smooth sailing, it's essential to grasp a few file-based routing naming conventions and concepts.
src/pages
) to store your Vue components (.vue
files). The plugin scans this folder and creates routes based on the filenames. This convention eliminates the need for a complex routes
configuration file.src/pages/index.vue
becomes /
(your app's home)src/pages/about.vue
becomes /about
(your About page)src/pages
creates nested routes. Imagine a folder named users
containing index.vue
and [id].vue
. This translates to:
/users
renders src/pages/users/index.vue
(your Users list)/users/:id
renders src/pages/users/[id].vue
(a dynamic route for an individual user, with :id
becoming a route parameter).src/pages/[...path].vue
. This file handles any unmatched route and typically displays a custom 404 "Not Found" page.Sure, unplugin-vue-router
appears to offer a seamless solution, almost too good to resist implementing straight into your production pipeline. Yet, before fully committing to its allure, it's crucial to address some essential considerations.
^4.1.0
or higher.tsconfig.json
file to include the vue-router/auto
for type safety.Automatic file-based routing with Vue Router is possible with unplugin-vue-router
. This package offers a compelling approach to route management in Vue.js applications. It reduces boilerplate code, improves maintainability, and promotes a clean code structure. With TypeScript support, you can ensure type safety in your route definitions. If you're looking to streamline your development workflow and enhance the organization of your Vue.js projects, unplugin-vue-router
is definitely worth exploring. Finally, remember we’ve got a complete course dedicated to this topic that goes even deeper than this article. Watch the Enhanced Routing with UnPlugin Vue Router course now!
Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.
More than 200.000 users have already joined us. You are welcome too!
© All rights reserved. Made with ❤️ by BitterBrains, Inc.