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

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

Mostafa Said
Mostafa Said
Updated: June 2nd 2024

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?

File-Based Routing with Vue.js Illustration Graph

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-router automatically 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/pages directory. This structure aligns perfectly with automatic file-based routing, promoting a clean and organized codebase.
  • Type Safety with TypeScript: 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.
  • Improved Performance with Lazy Loading: By default, 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.

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-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.

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.

  1. Convention Over Configuration: This approach uses a designated folder (named 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.
  2. File Naming Matters: The file names become the URL paths for your routes. For example:
    • src/pages/index.vue becomes / (your app's home)
    • src/pages/about.vue becomes /about (your About page)
  3. Directory Structure Matters Too: Nested directories within src/pages creates nested routes. Imagine a folder named users containing index.vue and [id].vue. This translates to:
    • The route /users renders src/pages/users/index.vue (your Users list)
    • The route /users/:id renders src/pages/users/[id].vue (a dynamic route for an individual user, with :id becoming a route parameter).
  4. 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.0 or higher.
  • After installing the plugin, you need to run your development server first and update your tsconfig.json file to include the vue-router/auto for 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

Mostafa Said
Mostafa Said
With over 7 years of e-learning expertise honed at major companies like Vodafone Intelligent Solutions (_VOIS), Mostafa is full-time instructor at Vue School and a full-stack developer in the wild. He built and maintained dozens of apps using Vue, Nuxt, Laravel, Tailwind, and more. He merges modern teaching methods with coding education to empower aspiring developers of all experience levels. When he's not glued to the code editor, hackathons fuel his competitive spirit, with Deepgram and Appwrite grand prizes under his belt.

Comments

Latest Vue School Articles

Developing a Full Stack Nuxt App with Bolt.new – An AI Experiment

Developing a Full Stack Nuxt App with Bolt.new – An AI Experiment

Use bolt.new to quickly iterate on a new Nuxt project. Learn how in this article, where we bootstrap a custom blog in no time!
Daniel Kelly
Daniel Kelly
Upgrading Eslint from v8 to v9 in Vue.js

Upgrading Eslint from v8 to v9 in Vue.js

Learn how to upgrade ESLint to v9 in Vue.js, taking advantage of the new flat configuration system and other significant changes in ESLint 9.0.
Mostafa Said
Mostafa Said

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!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.