Automatic File-Based Routing in Vue.js with TypeScript Support

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.
What is unplugin-vue-router?
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.
Why Use Automatic File-Based Routing?

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:
- Reduced Boilerplate: Say goodbye to manually writing route configurations.
unplugin-vue-routerautomatically generates routes based on the file structure, saving time and effort. - Improved Maintainability: As your application grows, managing a large number of route configurations can become challenging. Automatic file-based routing keeps your routes in sync with your components, making your codebase easier to maintain.
- Better Organization: By convention, page components reside in the
src/pagesdirectory. This structure aligns perfectly with automatic file-based routing, promoting a clean and organized codebase. - Type Safety with TypeScript:
unplugin-vue-routerprovides excellent support for TypeScript, ensuring type safety in your route definitions. Enjoy detecting invalid routes in real-time and autocompletion for links. - Improved Performance with Lazy Loading: By default,
unplugin-vue-routeruses 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.
Getting Started With unplugin-vue-router
Let's dive into how to set up and use unplugin-vue-router in a Vue.js 3 Vite project with TypeScript support.
Installation and configuration
The first thing we need to do is to install the package via npm or your preferred package manage:
npm i -D unplugin-vue-routerThis 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.
File based routing with Vue Router
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.
- Convention Over Configuration: This approach uses a designated folder (named
src/pages) to store your Vue components (.vuefiles). The plugin scans this folder and creates routes based on the filenames. This convention eliminates the need for a complexroutesconfiguration file. - File Naming Matters: The file names become the URL paths for your routes. For example:
src/pages/index.vuebecomes/(your app's home)src/pages/about.vuebecomes/about(your About page)
- Directory Structure Matters Too: Nested directories within
src/pagescreates nested routes. Imagine a folder nameduserscontainingindex.vueand[id].vue. This translates to:- The route
/usersrenderssrc/pages/users/index.vue(your Users list) - The route
/users/:idrenderssrc/pages/users/[id].vue(a dynamic route for an individual user, with:idbecoming a route parameter).
- The route
- Catch-All for Unmatched Routes (404): For unmatched URLs, create a catch-all route using
src/pages/[...path].vue. This file handles any unmatched route and typically displays a custom 404 "Not Found" page.
Important Considerations:
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.
- The plugin is still under development, so be aware of potential breaking changes or limitations.
- It requires Vue Router version
^4.1.0or higher. - After installing the plugin, you need to run your development server first and update your
tsconfig.jsonfile to include thevue-router/autofor type safety. - While the plugin simplifies development, it’s important to prioritize clear and descriptive route paths for optimal SEO. This helps search engines crawl and index your application effectively.
Conclusion
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!
Start learning Vue.js for free

Comments
Latest Vue School Articles
5 Component Design Patterns to Boost Your Vue.js Applications

Vibe Coding a Collaborative Editor with Comment Support with Nuxt UI and Jazz

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.


