Skip to content

Commit

Permalink
fix: require explicit routes import to avoid cyclic imports
Browse files Browse the repository at this point in the history
Fix #132

BREAKING CHANGE: `createRouter()` now requires the explicit `router`
property to be set and imported:

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

createRouter({
  history: createWebHistory(),
+  routes
})
```

This also means that runtime `extendRoutes()` option is not needed. It
has been deprecated and will be removed in the next major release.
  • Loading branch information
posva committed May 28, 2024
1 parent 85d8472 commit 63788f6
Show file tree
Hide file tree
Showing 10 changed files with 43 additions and 40 deletions.
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,7 @@ If you don't have an `env.d.ts` file, you can create one and add the unplugin-vu
{
"compilerOptions": {
// ...
"types": [
"unplugin-vue-router/client"
]
"types": ["unplugin-vue-router/client"]
}
}
```
Expand All @@ -161,11 +159,12 @@ Finally, you should replace your imports from `vue-router` to `vue-router/auto`:
```diff
-import { createRouter, createWebHistory } from 'vue-router'
+import { createRouter, createWebHistory } from 'vue-router/auto'
+import { routes } from 'vue-router/auto-routes'

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

Expand Down
31 changes: 16 additions & 15 deletions docs/guide/extending-routes.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,37 +89,38 @@ The `<route>` custom block is a way to extend existing routes. It can be used to

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.

## `extendRoutes()`
## Extending routes at runtime

As an escape-hatch, it's possible to extend the routes **at runtime** with the `extendRoutes` option in `createRouter()`. Since these changes are made at runtime, they are not reflected in the generated `typed-router.d.ts` file.
As an escape-hatch, it's possible to extend the routes **at runtime** by simply changing the `routes` array before passing it to `createRouter()`. Since these changes are made at runtime, they are not reflected in the generated `typed-router.d.ts` file.

```js{4-12}
```js{4-9}
import { createWebHistory, createRouter } from 'vue-router/auto'
import { routes } from 'vue-router/auto-routes'
for (const route of routes) {
if (route.name === '/admin') {
adminRoute.meta ??= {}
adminRoute.meta.requiresAuth = true
}
}
const router = createRouter({
extendRoutes: (routes) => {
const adminRoute = routes.find((r) => r.name === '/admin')
if (adminRoute) {
adminRoute.meta ??= {}
adminRoute.meta.requiresAuth = true
}
// the return is completely optional since we are modifying the routes in place
return routes
},
history: createWebHistory(),
routes,
})
```

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

One example of this is using [vite-plugin-vue-layouts](https://github.com/JohnCampionJr/vite-plugin-vue-layouts) which can only be used alongside `extendRoutes()`:
One example of this is using [vite-plugin-vue-layouts](https://github.com/JohnCampionJr/vite-plugin-vue-layouts) which can only be used this way:

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

const router = createRouter({
// ...
extendRoutes: (routes) => setupLayouts(routes),
routes: setupLayouts(routes),
})
```
11 changes: 7 additions & 4 deletions docs/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ Given the following route configuration:
```ts [src/router.ts]
import { createRouter, createWebHistory } from 'vue-router' // [!code --]
import { createRouter, createWebHistory } from 'vue-router/auto' // [!code ++]
import { routes } from 'vue-router/auto-routes' // [!code ++]
export const router = createRouter({
history: createWebHistory(),
Expand All @@ -196,6 +197,7 @@ export const router = createRouter({
component: () => import('src/pages/About.vue'), // [!code --]
}, // [!code --]
] // [!code --]
routes, // [!code ++]
})
```

Expand All @@ -222,14 +224,15 @@ Check the [file-based routing](/guide/file-based-routing) guide for more informa

::: code-group

```ts{2,5-8,11} [src/main.ts]
```ts{2-3,6-9,12} [src/main.ts]
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(),
// the routes property is handled by the plugin
routes,
})
createApp(App)
Expand All @@ -247,9 +250,9 @@ createApp(App)

Check the [file-based routing](/guide/file-based-routing) guide for more information about the naming conventions.

### Passing the routes manually
### Manipulating the 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](https://github.com/antfu/vitesse/blob/main/src/main.ts):
You can pass the `routes` to any plugin that needs to add changes to them but note that **these changes will not be reflected in types**. Use [build-time routes instead](./guide//extending-routes.md) if you want to have types support. Here is an example with [Vitesse starter](https://github.com/antfu/vitesse/blob/main/src/main.ts):

```ts
import { ViteSSG } from 'vite-ssg'
Expand Down
1 change: 1 addition & 0 deletions docs/rfcs/data-loaders/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,7 @@ import { DataLoaderPlugin, createRouter, createWebHistory } from 'vue-router/aut
const app = createApp({})
const router = createRouter({
history: createWebHistory(),
routes: [],
})
// ---cut---
// @moduleResolution: bundler
Expand Down
6 changes: 2 additions & 4 deletions playground/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ import {
createWebHistory,
DataLoaderPlugin,
} from 'vue-router/auto'
import { routes } from 'vue-router/auto-routes'
import { MutationCache, QueryCache, VueQueryPlugin } from '@tanstack/vue-query'
import { createPinia } from 'pinia'
import { QueryPlugin } from '@pinia/colada'

const router = createRouter({
history: createWebHistory(),
extendRoutes: (routes) => {
// routes.find((r) => r.name === '/')!.meta = {}
return routes
},
routes,
})

const app = createApp(App)
Expand Down
10 changes: 7 additions & 3 deletions src/codegen/vueRouterModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export function generateVueRouterProxy(
{ addPiniaColada }: { addPiniaColada: boolean }
) {
return `
import { routes } from '${routesModule}'
import { createRouter as _createRouter } from 'vue-router'
export * from 'vue-router'
Expand All @@ -24,14 +23,19 @@ export * from 'unplugin-vue-router/data-loaders/basic'
${addPiniaColada ? "export * from 'unplugin-vue-router/data-loaders/pinia-colada'" : ''}
export function createRouter(options) {
const { extendRoutes } = options
const { extendRoutes, routes } = options
// use Object.assign for better browser support
if (extendRoutes) {
console.warn('"extendRoutes()" is deprecated, please modify the routes directly. See')
}
const router = _createRouter(Object.assign(
options,
{ routes: typeof extendRoutes === 'function' ? extendRoutes(routes) : routes },
{ routes: typeof extendRoutes === 'function' ? (extendRoutes(routes) || routes) : routes },
))
return router
}
`.trimStart()
}

// FIXME: remove `extendRoutes()` in the next major version
2 changes: 1 addition & 1 deletion src/core/vite/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ViteDevServer } from 'vite'
import { type ViteDevServer } from 'vite'
import { ServerContext } from '../../options'
import { asVirtualId } from '../moduleConstants'

Expand Down
8 changes: 1 addition & 7 deletions src/data-loaders/navigation-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,14 +325,8 @@ export class NavigationResult {
*
* @example
* ```ts
* import { createApp } from 'vue'
* import {
* createRouter,
* DataLoaderPlugin,
* createWebHistory,
* } from 'vue-router/auto'
*
* const router = createRouter({
* routes,
* history: createWebHistory(),
* })
*
Expand Down
4 changes: 3 additions & 1 deletion src/type-extensions/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,14 @@ export type _Router =

/**
* unplugin-vue-router version of `RouterOptions`.
* @deprecated use `RouterOptions` instead. This type is no longer needed.
* @see {@link RouterOptions}
*/
export interface _RouterOptions extends Omit<RouterOptions, 'routes'> {
export interface _RouterOptions extends RouterOptions {
/**
* Modify the routes before they are passed to the router. You can modify the existing array or return a
* new one.
* @deprecated `routes` is now required, so you can just modify a copy of the array directly.
*
* @param routes - The routes generated by this plugin and exposed by `vue-router/auto-routes`
*/
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export type {
// TODO: deprecate and remove
_RouterTyped,
_Router as Router,
// FIXME: remove in the next major version
_RouterOptions,
} from './type-extensions/router'
export type {
Expand Down

0 comments on commit 63788f6

Please sign in to comment.