• Stars
    star
    1,643
  • Rank 28,446 (Top 0.6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 2 years ago
  • Updated 26 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Next Generation file based typed routing for Vue Router

unplugin-vue-router

NPM version ci status

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 at least 4.1.0.

⚠️ This package is still experimental. If you found any issue, design flaw, or have ideas to improve it, please, 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 should replace your imports from vue-router to vue-router/auto:

-import { createRouter, createWebHistory } from 'vue-router'
+import { createRouter, createWebHistory } from 'vue-router/auto'

createRouter({
  history: createWebHistory(),
  // You don't need to pass the routes anymore,
  // the plugin writes it for you 🤖
})

Note
You can exclude vue-router from VSCode import suggestions by adding this setting to your .vscode/settings.json:

{
  "typescript.preferences.autoImportFileExcludePatterns": ["vue-router"]
}

This will ensure VSCode only suggests vue-router/auto for imports. Alternatively, you can also configure auto imports.

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))
   },
 )

Auto Imports

If you are using unplugin-auto-import, make sure to remove the vue-router preset and use the one exported by unplugin-vue-router:

 import { defineConfig } from 'vite'
 import AutoImport from 'unplugin-auto-import/vite'
+import { VueRouterAutoImports } from 'unplugin-vue-router'

 export default defineConfig({
   plugins: [
     // other plugins
     AutoImport({
       imports: [
-        'vue-router',
+        VueRouterAutoImports,
       ],
     }),
   ],
 })

Note that the vue-router preset might export less things than the one exported by unplugin-vue-router so you might need to add any other imports you were relying on manually:

     AutoImport({
       imports: [
-        'vue-router',
+        VueRouterAutoImports,
+        {
+           // add any other imports you were relying on
+           'vue-router/auto': ['useLink']
+        },
       ],
     }),

Make sure to also check and follow the TypeScript section below if you are using TypeScript or have a jsconfig.json file.

Configuration

Have a glimpse of all the existing configuration options with their corresponding default values:

VueRouter({
  // Folder(s) to scan for vue components and generate routes. Can be a string, or
  // an object, or an array of those. Each option allows to override global options.
  // like exclude, extensions, etc.
  routesFolder: 'src/pages',

  // allowed extensions for components to be considered as pages
  // can also be a suffix: e.g. `.page.vue` will match `home.page.vue`
  // but remove it from the route path
  extensions: ['.vue'],

  // list of glob files to exclude from the routes generation
  // e.g. ['**/__*'] will exclude all files and folders starting with `__`
  // e.g. ['**/__*/**/*'] will exclude all files within folders starting with `__`
  // e.g. ['**/*.component.vue'] will exclude components ending with `.component.vue`
  exclude: [],

  // Path for the generated types. Defaults to `./typed-router.d.ts` if typescript
  // is installed. Can be disabled by passing `false`.
  dts: './typed-router.d.ts',

  // Override the name generation of routes. unplugin-vue-router exports two versions:
  // `getFileBasedRouteName()` (the default) and `getPascalCaseRouteName()`. Import any
  // of them within your `vite.config.ts` file.
  getRouteName: (routeNode) => myOwnGenerateRouteName(routeNode),

  // Customizes the default langage for `<route>` blocks
  // json5 is just a more permissive version of json
  routeBlockLang: 'json5',

  // Change the import mode of page components. Can be 'async', 'sync', or a function with the following signature:
  // (filepath: string) => 'async' | 'sync'
  importMode: 'async',
})

Routes folder structure

By default, this plugins checks the folder at src/pages for any .vue files and generates the corresponding routing structure basing itself in the file name. This way, you no longer need to maintain a routes array when adding routes to your application, instead just add the new .vue component to the routes folder and let this plugin do the rest!

Let's take a look at a simple example:

src/pages/
├── index.vue
├── about.vue
└── users/
    ├── index.vue
    └── [id].vue

This will generate the following routes:

  • /: -> renders the index.vue component
  • /about: -> renders the about.vue component
  • /users: -> renders the users/index.vue component
  • /users/:id: -> renders the users/[id].vue component. id becomes a route param.

Index Routes

Any index.vue file will generate an empty path (similar to index.html files):

  • src/pages/index.vue: generates a / route
  • src/pages/users/index.vue: generates a /users route

Nested Routes

Nested routes are automatically defined by defining a .vue file alongside a folder with the same name. If you create both a src/pages/users/index.vue and a src/pages/users.vue components, the src/pages/users/index.vue will be rendered within the src/pages/users.vue's <RouterView>.

In other words, given this folder structure:

src/pages/
├── users/
│   └── index.vue
└── users.vue

You will get this routes array:

const routes = [
  {
    path: '/users',
    component: () => import('src/pages/users.vue'),
    children: [
      { path: '', component: () => import('src/pages/users/index.vue') },
    ],
  },
]

While omitting the src/pages/users.vue component will generate the following routes:

const routes = [
  {
    path: '/users',
    // notice how there is no component here
    children: [
      { path: '', component: () => import('src/pages/users/index.vue') },
    ],
  },
]

Note the folder and file's name users/ could be any valid naming like my-[id]-param/.

Nested routes without nesting layouts

Sometimes you might want to add nesting to the URL in the form of slashes but you don't want it to impact your UI hierarchy. Consider the following folder structure:

src/pages/
├── users/
│   ├── [id].vue
│   └── index.vue
└── users.vue

If you want to add a new route /users/create you could add a new file src/pages/users/create.vue but that would nest the create.vue component within the users.vue component. To avoid this you can instead create a file src/pages/users.create.vue. The . will become a / when generating the routes:

const routes = [
  {
    path: '/users',
    component: () => import('src/pages/users.vue'),
    children: [
      { path: '', component: () => import('src/pages/users/index.vue') },
      { path: ':id', component: () => import('src/pages/users/[id].vue') },
    ],
  },
  {
    path: '/users/create',
    component: () => import('src/pages/users.create.vue'),
  },
]

Named routes

All generated routes that have a component property will have a name property. This avoid accidentally directing your users to a parent route. By default, names are generated using the file path, but you can override this behavior by passing a custom getRouteName() function. You will get TypeScript validation almost everywhere, so changing this should be easy.

Dynamic Routes

You can add route params by wrapping the param name with brackets, e.g. src/pages/users/[id].vue will create a route with the following path: /users/:id. Note you can add a param in the middle in between static segments: src/pages/users_[id].vue -> /users_:id. You can even add multiple params: src/pages/product_[skuId]_[seoDescription].vue.

You can create optional params by wrapping the param name with an extra pair of brackets, e.g. src/pages/users/[[id]].vue will create a route with the following path: /users/:id?.

You can create repeatable params by adding a plus character (+) after the closing bracket, e.g. src/pages/articles/[slugs]+.vue will create a route with the following path: /articles/:slugs+.

And you can combine both to create optional repeatable params, e.g. src/pages/articles/[[slugs]]+.vue will create a route with the following path: /articles/:slugs*.

Catch all / 404 Not found route

To create a catch all route prepend 3 dots (...) to the param name, e.g. src/pages/[...path].vue will create a route with the following path: /:path(.*). This will match any route. Note this can be done inside a folder too, e.g. src/pages/articles/[...path].vue will create a route with the following path: /articles/:path(.*).

Multiple routes folders

It's possible to provide multiple routes folders by passing an array to routesFolder:

VueRouter({
  routesFolder: ['src/pages', 'src/admin/routes'],
})

You can also provide a path prefix for each of these folders, it will be used as is, and cannot start with a / but can contain any params you want or even not finish with a /:

VueRouter({
  routesFolder: [
    'src/pages',
    {
      src: 'src/admin/routes',
      // note there is always a trailing slash and never a leading one
      path: 'admin/',
      // src/admin/routes/dashboard.vue -> /admin/dashboard
    },
    {
      src: 'src/docs',
      // you can add parameters
      path: 'docs/:lang/',
      // src/docs/introduction.vue -> /docs/:lang/introduction
    },
    {
      src: 'src/promos',
      // you can omit the trailing slash
      path: 'promos-',
      // src/promos/black-friday.vue -> /promos-black-friday
    },
  ],
})

Note that the provided folders must be separate and one route folder cannot contain another specified route folder. If you need further customization, give definePage() a try.

TypeScript

This plugin generates a d.ts file with all the typing overrides when the dev or build server is ran. Make sure to include it in your tsconfig.json's (or jsconfig.json's) include or files property:

{
  // ...
  "include": [/* ... */ "typed-router.d.ts"]
  // ...
}

Then, you will be able to import from vue-router/auto (instead of vue-router) to get access to the typed APIs. You can commit the typed-router.d.ts file to your repository to make your life easier.

Extra types

You can always take a look at the generated typed-router.d.ts file to inspect what are the generated types. unplugin-vue-router improves upon many of the existing types in vue-router and adds a few ones as well:

RouteNamedMap

The RouteNamedMap interface gives you access to all the metadata associated with a route. It can also be extended to enable types for dynamic routes that are added during runtime.

import type { RouteNamedMap } from 'vue-router/auto/routes'

Extending types with dynamically added routes:

declare module 'vue-router/auto/routes' {
  import type {
    RouteRecordInfo,
    ParamValue,
    // these are other param helper types
    ParamValueOneOrMore,
    ParamValueZeroOrMore,
    ParamValueZeroOrOne,
  } from 'unplugin-vue-router'
  export interface RouteNamedMap {
    // the key is the name and should match the first generic of RouteRecordInfo
    'custom-dynamic-name': RouteRecordInfo<
      'custom-dynamic-name',
      '/added-during-runtime/[...path]',
      // these are the raw param types (accept numbers, strings, booleans, etc)
      { path: ParamValue<true> },
      // these are the normalized params as found in useRoute().params
      { path: ParamValue<false> }
    >
  }
}

RouterTyped

The RouterTyped type gives you access to the typed version of the router instance. It's also the ReturnType of the useRouter() function.

import type { RouterTyped } from 'vue-router/auto'

RouteLocationResolved

The RouteLocationResolved type exposed by vue-router/auto allows passing a generic (which autocomplete) to type a route whenever checking the name doesn't makes sense because you know the type. This is useful for cases like <RouterLink v-slot="{ route }">:

<RouterLink v-slot="{ route }">
  User {{ (route as RouteLocationResolved<'/users/[id]'>).params.id }}
</RouterLink>

This type is also the return type of router.resolve().

You have the same equivalents for RouteLocation, RouteLocationNormalized, and RouteLocationNormalizedLoaded. All of them exist in vue-router but vue-router/auto override them to provide a type safe version of them. In addition to that, you can pass the name of the route as a generic:

// these are all valid
let userWithId: RouteLocationNormalizedLoaded<'/users/[id]'> = useRoute()
userWithId = useRoute<'/users/[id]'>()
// 👇 this one is the easiest to write because it autocomplete
userWithId = useRoute('/users/[id]')

Named views

It is possible to define named views by appending an @ + a name to their filename, e.g. a file named src/pages/[email protected] will generate a route of:

{
  path: '/',
  component: {
    aux: () => import('src/pages/[email protected]')
  }
}

Note that by default a non named route is named default and that you don't need to name your file [email protected] even if there are other named views (e.g. having [email protected] and index.vue is the same as having [email protected] and [email protected]).

Extending existing routes

definePage() in <script>

The macro definePage() allows you to define any extra properties related to the route. It is useful when you need to customize the path, the name, meta, etc

<script setup>
import { definePage } from 'vue-router/auto'

definePage({
  name: 'my-own-name',
  path: '/absolute-with-:param',
  alias: ['/a/:param'],
  meta: {
    custom: 'data',
  },
})
</script>

Note you cannot use variables in definePage() as its passed parameter gets extracted at build time and is removed from <script setup>. You can also use the <route> block which allows other formats like yaml.

SFC <route> custom block

The <route> custom block is a way to extend existing routes. It can be used to add new meta fields, override the path, the name, or anything else in a route. It has to be added to a .vue component inside of the routes folder. It is similar to the same feature in vite-plugin-pages to facilitate migration.

<route lang="json">
{
  "name": "name-override",
  "meta": {
    "requiresAuth": false
  }
}
</route>

Note you can specify the language to use with <route lang="yaml">. By default, the language is JSON5 (more flexible version of JSON) but yaml and JSON are also supported. This will also add Syntax Highlighting.

extendRoutes()

You can extend existing routes by passing an extendRoutes function to createRouter(). This should be used as a last resort (or until a feature is natively available here):

import { createWebHistory, createRouter } from 'vue-router/auto'

const router = createRouter({
  extendRoutes: (routes) => {
    const adminRoute = routes.find((r) => r.name === '/admin')
    if (adminRoute) {
      adminRoute.meta ??= {}
      adminRoute.meta.requiresAuth = true
    }
    // completely optional since we are modifying the routes in place
    return routes
  },
  history: createWebHistory(),
})

As this plugin evolves, this function should be used less and less and only become necessary in unique edge cases.

One example of this is using vite-plugin-vue-layouts which can only be used alongside extendRoutes():

import { createRouter } from 'vue-router/auto'
import { setupLayouts } from 'virtual:generated-layouts'

const router = createRouter({
  // ...
  extendRoutes: (routes) => setupLayouts(routes),
})

Rationale

This project idea came from trying to type the router directly using Typescript, finding out it's not fast enough to be pleasant to use and, ending up using build-based tools, taking some inspiration from other projects like:

License

MIT

More Repositories

1

vue-promised

💝 Composable Promises & Promises as components
TypeScript
1,792
star
2

vim-vue

Syntax Highlight for Vue.js components
Vim Script
1,286
star
3

catimg

🦦 Insanely fast image printing in your terminal
C
1,239
star
4

vue-mdc

Material web components for Vue.js
JavaScript
1,201
star
5

mande

<700 bytes convenient and modern wrapper around fetch with smart extensible defaults
TypeScript
1,188
star
6

pinia-colada

🍹 The smart data fetching layer for Pinia
TypeScript
764
star
7

vuexfire

Check
JavaScript
559
star
8

vite-tailwind-starter

Starter using Vite + Tailwind for super fast prototyping
Vue
459
star
9

vuex-mock-store

✅Simple and straightforward Vuex Store mock for vue-test-utils
JavaScript
273
star
10

focus-trap-vue

Vue component to trap the focus within a DOM element
JavaScript
204
star
11

vue-router-mock

🧪 Easily mock routing interactions in your Vue apps
TypeScript
198
star
12

vue-plugin-template

🚀 Solid foundation to start a Vue plugin with the best developer experience and a focus on performance
JavaScript
192
star
13

vue-local-scope

🖇 Generate local scopes in templates to compute data from other scoped slots or simply to have variables in templates
JavaScript
168
star
14

vue-reactive-refs

Make $refs reactive so they can be used in computed properties and watchers
TypeScript
160
star
15

vue-ts-lib

Vue 3 library starter in TS with lint, auto release, changelog and tests
JavaScript
160
star
16

sounds-webpack-plugin

🔊Notify or errors, warnings, etc with sounds
JavaScript
124
star
17

vue-tweezing

💃 Easy, customizable and automatic tweening nicely served in scoped slots
JavaScript
100
star
18

vue-use-spring

💫 Naturally fluid animations for Vue
TypeScript
89
star
19

vue-compose-promise

💝 Promises using vue composition api
TypeScript
76
star
20

vue-coerce-props

Coerce props to whatever you want
JavaScript
75
star
21

shapify

🌀Easily transform objects/rename keys with full TypeScript support
JavaScript
67
star
22

pinia-plugin-debounce

Config-based action debouncing made easy
TypeScript
65
star
23

markdown-it-custom-block

Handle custom blocks transformations for markdown-it
JavaScript
53
star
24

state-animation-demos

Demos for Vue.js amsterdam/roadtrip talk: State animations, getting them right
Vue
43
star
25

task-logger.sh

🎨 shell library to log tasks with nice output. Supports zsh and bash
Shell
43
star
26

vue-router-view-transition

Properly time out-in transitions with scrollBehavior
JavaScript
40
star
27

event-emitter

<200 bytes type safe extendable event emitter / pubsub class
TypeScript
39
star
28

vuefire-nuxt-example

Example project using VueFire with Nuxt
Vue
33
star
29

vuefire-emoji-panel

Nuxt + VueFire Demo code
TypeScript
32
star
30

vue-prop-data-fallback

Vue mixin to support an optional prop by falling back to a local data
JavaScript
31
star
31

size-check-action

A custom size action
TypeScript
28
star
32

nuxt--vuefire-example-spark-plan

🔥 Nuxt + VueFire template to bootstrap your Firebase App
Vue
26
star
33

2021-amsterdam-demos

Vue
25
star
34

rollit

🌯 Zero config js library bundling using rollup with support for Vue
JavaScript
24
star
35

unplugin-vue-router-demo

Demo for the talk "Stop writing your routes"
TypeScript
23
star
36

vuefire-vite-example

Example project using VueFire in a vite project
Vue
23
star
37

talk-vuejs-and-typescript-a-complicated-relationship

Talk Vue.js and Typescript, a complicated relationship
22
star
38

vue-recomputed

Recomputable computed properties
JavaScript
21
star
39

talk-data-loaders

Slides and demo code for Vue.js Live talk
TypeScript
20
star
40

onlysponsors

Tracker for Only Sponsors
20
star
41

nuxt--vuefire-example-blaze-plan

🔥 Nuxt + VueFire template to bootstrap your Firebase App with the Blaze plan
Vue
20
star
42

p-singleton

Ensure only one instance of a promise is created until rejected or resolved
JavaScript
19
star
43

clipboard-text

Simple and small copy-text-to-the-clipboard-utility with IE11 support
TypeScript
13
star
44

how2

Exercise building a scalable web app like how2 cli using Vue
JavaScript
12
star
45

faked-promise

Create a fake promise that can be resolve and rejected programatically
JavaScript
11
star
46

lib-boilerplate-ts

personal boilerplate for a lib with ts
JavaScript
11
star
47

esm.dev

👨‍💻 my personal website
TypeScript
10
star
48

jest-mock-warn

Mock console.log warn calls and assert their calls
JavaScript
10
star
49

paths.esm.dev

🛣 A Vue Router path debugger
Vue
10
star
50

dotfiles

📁 My dotfiles
Vim Script
9
star
51

phaser-webpack-ts

Starter for Phaser 3 with Typescript, webpack and weback DLLPlugin
JavaScript
8
star
52

mocha-requirejs-boilerplate

JavaScript
7
star
53

mocha-css

A mocha stylesheet for the HTML reporter that let you append visual tests
CSS
7
star
54

eslint-config-posva

🤺 Opinionated eslint set of rules with support for Vue
JavaScript
7
star
55

vitesse-unplugin-vue-router

Test repo for unplugin-vue-router + vitesse
TypeScript
6
star
56

vitepress-theme-nuxt-content

Vitepress theme imitating Nuxt Content
Vue
5
star
57

minesweeper.rs

Learning project with Rust: Minesweeper
Rust
5
star
58

free-workshop-pinia-from-scratch

Free online workshop to build Pinia from scratch
TypeScript
5
star
59

renovate-config

Renovate config for Open Source
5
star
60

nuxt--vuefire-demo

Nuxt VueFire Demo
Vue
5
star
61

pinia-ssr-example-cw

TypeScript
4
star
62

OUTDATED_nuxt-vuefire-example

wip
Vue
4
star
63

instacraper

Scrap images from Instagram post
JavaScript
4
star
64

vercel-nuxt-example

Vue
3
star
65

vue-pinia-example

Created with CodeSandbox
JavaScript
3
star
66

vuefire-core

mirror to test something with codecov
JavaScript
3
star
67

vuefire-vitesse-example

Example of using VueFire with SSR
TypeScript
3
star
68

slides

📢 Talks I have given somewhere, sometime
HTML
2
star
69

store-code-split-demo

demo to showcase ideal codesplit for a store like Vuex
JavaScript
2
star
70

bug-vue-loader-slot

Vue
2
star
71

bug-report-vca

JavaScript
2
star
72

pinia-colada-example

Example repository for stackblitz
Vue
2
star
73

demo-data-loaders-artwork-gallery

TypeScript
2
star
74

nuxt-composition-api-185

Vue
2
star
75

configure-script

⚡ Simple script to generate Makefiles for your project. It's mainly aimed for C/C++ but can be adapted to other languages
Shell
2
star
76

.github

Default .github folder
2
star
77

vuefire-examples

Various examples showcasing vuefire/vuexfire
HTML
2
star
78

2d-collisions

Collision for 2D using the SAT theorem with Rectangles
C++
2
star
79

mille-bornes

mille bornes card game for 2 players only with AI and online
CoffeeScript
1
star
80

blog.esm.dev

Vue
1
star
81

awesome-latex-workspace

📑 Watcher + commit based diff generator
Shell
1
star
82

vue-merge-options

Helpers to merge vue custom options
1
star
83

mangare-angular

🍙 Download Manga in convenient formats!
JavaScript
1
star
84

bug-report-nuxt-plugin

TypeScript
1
star
85

bcn-marfeel-demo

Demo for the meetup @marfeel the 19/07/2018
Vue
1
star
86

Rndm

Random number generation for vim
Vim Script
1
star
87

portfolio

1
star
88

planet-noise

Test to generate planet terrain using libnoise. SFML to render the image
C++
1
star
89

app-dep-test-renovate

JavaScript
1
star
90

lerna-test

Testing things with lerna
JavaScript
1
star
91

imag-utils

Scripts ou autres infos utiles à l'Ensimag
JavaScript
1
star
92

literate-couscous

1
star
93

lab-vue-getting-started

tech.io lab
JavaScript
1
star
94

tetris

⬛ A simple engine of tetris that can be used along with another printing system
C
1
star
95

pretty-hrtime.sh

🕒 Pretty High Resolution Time in shell
Shell
1
star
96

nuxt--vuefire-repro-template

Nuxt VueFire template for reproductions
Vue
1
star
97

posva

🌮🌮🌮
1
star
98

app-dep-test

JavaScript
1
star
99

test-pr-lib

JavaScript
1
star
100

MangaDown

Allow to download mangas from websites using a parsing file
C++
1
star