Skip to content

Commit

Permalink
fix(types): use vue-router/auto-routes
Browse files Browse the repository at this point in the history
BREAKING CHANGE: This change was necessary to improve compatibility with
TypeScript and other tools in the ecosystem. Most of the time you don't
need to use this path but if you were using it, replace it:

```diff
- import { } from 'vue-router/auto/routes'
+ import { } from 'vue-router/auto-routes'
```
  • Loading branch information
posva committed Jan 19, 2024
1 parent 683b0a1 commit 2dc0446
Show file tree
Hide file tree
Showing 10 changed files with 16 additions and 148 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ Alternatively, **you can also import the `routes` array** and create the router
import App from './App.vue'
import type { UserModule } from './types'
-import generatedRoutes from '~pages'
+import { routes } from 'vue-router/auto/routes'
+import { routes } from 'vue-router/auto-routes'

import '@unocss/reset/tailwind.css'
import './styles/main.css'
Expand Down Expand Up @@ -447,13 +447,13 @@ You can always take a look at the generated `typed-router.d.ts` file to inspect
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.

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

Extending types with dynamically added routes:

```ts
declare module 'vue-router/auto/routes' {
declare module 'vue-router/auto-routes' {
import type {
RouteRecordInfo,
ParamValue,
Expand All @@ -462,6 +462,7 @@ declare module 'vue-router/auto/routes' {
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<
Expand Down
2 changes: 1 addition & 1 deletion playground/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { useLink, useRoute } from 'vue-router/auto'
import type { RouteNamedMap } from 'vue-router/auto/routes'
import type { RouteNamedMap } from 'vue-router/auto-routes'
import type {
RouteLocationNormalizedLoaded,
RouteLocationResolved,
Expand Down
2 changes: 1 addition & 1 deletion playground/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
RouteLocationNormalizedLoaded,
} from 'vue-router/auto'
import { viewDepthKey, useRoute, useRouter } from 'vue-router/auto'
import type { RouteNamedMap } from 'vue-router/auto/routes'
import type { RouteNamedMap } from 'vue-router/auto-routes'

type NavigationReturn = RouteLocation | boolean | void

Expand Down
5 changes: 1 addition & 4 deletions playground/typed-router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
// It's recommended to commit this file.
// Make sure to add this file to your tsconfig.json file as an "includes" or "files" entry.



// export { }
declare module 'vue-router/auto-routes' {
import type {
RouteRecordInfo,
Expand All @@ -16,6 +13,7 @@ declare module 'vue-router/auto-routes' {
ParamValueZeroOrMore,
ParamValueZeroOrOne,
} from 'unplugin-vue-router/types'

/**
* Route name map generated by unplugin-vue-router
*/
Expand Down Expand Up @@ -67,4 +65,3 @@ declare module 'vue-router/auto-routes' {
'/with-extension': RouteRecordInfo<'/with-extension', '/with-extension', Record<never, never>, Record<never, never>>,
}
}

112 changes: 0 additions & 112 deletions src/codegen/generateDTS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,6 @@ declare module '${routesModule}' {
ParamValueZeroOrMore,
ParamValueZeroOrOne,
} from 'unplugin-vue-router/types'
import type { RouteRecordRaw } from 'vue-router'
/**
* Array of routes generated by unplugin-vue-router
*/
export const routes: RouteRecordRaw[]
/**
* Route name map generated by unplugin-vue-router
Expand All @@ -40,111 +34,5 @@ ${routeNamedMap
.map((line) => ' ' + line)
.join('\n')}
}
declare module '${vueRouterModule}' {
import type { RouteNamedMap } from '${routesModule}'
import type {
_RouterTyped,
_RouterOptions,
// typed routes helpers
RouteLocationTypedList,
RouteLocationResolvedTypedList,
RouteLocationNormalizedTypedList,
RouteLocationNormalizedLoadedTypedList,
RouteLocationAsString,
RouteLocationAsRelativeTypedList,
RouteLocationAsPathTypedList,
NavigationGuardTyped,
NavigationGuardWithThisTyped,
RouterLinkPropsTyped,
RouterLinkTyped,
UseLinkFnTyped,
} from 'unplugin-vue-router/types'
// reexport all types that are not augmented by unplugin-vue-router
export * from 'vue-router'
// Augmented types to override the ones exported by vue-router
export type {
Router,
RouteLocationNormalized,
RouteRecordName,
RouteLocationNormalizedLoaded,
RouteLocation,
RouteLocationAsRelativePath,
RouteLocationRaw,
RouteLocationResolved,
RouteParams,
RouteParamsRaw,
NavigationGuard,
NavigationGuardWithThis,
} from 'unplugin-vue-router/types'
/**
* @deprecated use \`Router\` instead. This type will be a different one in the next major version.
*/
export type RouterTyped = _RouterTyped<RouteNamedMap>
export function useRouter(): _RouterTyped<RouteNamedMap>
export function useRoute<
Name extends keyof RouteNamedMap = keyof RouteNamedMap
>(name?: Name): RouteLocationNormalizedLoadedTypedList<RouteNamedMap>[Name]
export const useLink: UseLinkFnTyped<RouteNamedMap>
export function onBeforeRouteLeave(guard: NavigationGuardTyped<RouteNamedMap>): void
export function onBeforeRouteUpdate(guard: NavigationGuardTyped<RouteNamedMap>): void
export const RouterLink: RouterLinkTyped<RouteNamedMap>
export const RouterLinkProps: RouterLinkPropsTyped<RouteNamedMap>
export function createRouter(options: _RouterOptions): _RouterTyped<RouteNamedMap>
// Experimental Data Fetching
export {
_definePage as definePage,
DataLoaderPlugin,
_setupLoaderGuard as setupLoaderGuard,
_defineBasicLoader as defineBasicLoader,
// FIXME: remove these in next major
_HasDataLoaderMeta as HasDataLoaderMeta,
_setupDataFetchingGuard as setupDataFetchingGuard,
_stopDataFetchingScope as stopDataFetchingScope,
} from 'unplugin-vue-router/runtime'
}
`.trimStart()
}

/**
* Generates the DTS that adds types to `TypesConfig` for unplugin-vue-router and vue-router. This file doesn't need to
* be generated but this way we can generate it for the user instead of letting them copy paste it.
*
* @param routesModule - The path to the routes module, e.g. `vue-router/auto/routes`
*/
export function generateTypesConfigDTS(routesModule: string) {
return `
import type {
_RouterOptions,
NavigationGuardTyped,
NavigationGuardWithThisTyped,
RouteLocationNormalizedLoadedTypedList,
_RouterTyped,
RouterLinkTyped,
} from 'unplugin-vue-router/types'
import type { RouteNamedMap } from '${routesModule}'
declare module 'unplugin-vue-router/types' {
export interface _TypesConfig {
RouteNamedMap: RouteNamedMap
}
}
declare module 'vue-router' {
export interface TypesConfig {
beforeRouteEnter: NavigationGuardWithThisTyped<undefined, RouteNamedMap>
beforeRouteUpdate: NavigationGuardTyped<RouteNamedMap>
beforeRouteLeave: NavigationGuardTyped<RouteNamedMap>
$route: RouteLocationNormalizedLoadedTypedList<RouteNamedMap>[keyof RouteNamedMap]
$router: _RouterTyped<RouteNamedMap>
RouterLink: RouterLinkTyped<RouteNamedMap>
}
}
`.trimStart()
}
2 changes: 1 addition & 1 deletion src/codegen/vueRouterModule.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// NOTE: this code needs to be generated because otherwise it doesn't go through transforms and `vue-router/auto/routes`
// NOTE: this code needs to be generated because otherwise it doesn't go through transforms and `vue-router/auto-routes`

import type { ResolvedOptions } from '../options'

Expand Down
24 changes: 3 additions & 21 deletions src/core/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ import {
HandlerContext,
resolveFolderOptions,
} from './RoutesFolderWatcher'
import {
generateDTS as _generateDTS,
generateTypesConfigDTS,
} from '../codegen/generateDTS'
import { generateDTS as _generateDTS } from '../codegen/generateDTS'
import { generateVueRouterProxy as _generateVueRouterProxy } from '../codegen/vueRouterModule'
import { hasNamedExports } from '../data-fetching/parse'
import { definePageTransform, extractDefinePageNameAndPath } from './definePage'
Expand Down Expand Up @@ -208,7 +205,7 @@ export function createRoutesContext(options: ResolvedOptions) {
})
}

// NOTE: this code needs to be generated because otherwise it doesn't go through transforms and `vue-router/auto/routes`
// NOTE: this code needs to be generated because otherwise it doesn't go through transforms and `vue-router/auto-routes`
// cannot be resolved.
function generateVueRouterProxy() {
return _generateVueRouterProxy(MODULE_ROUTES_PATH, options)
Expand All @@ -228,27 +225,12 @@ export function createRoutesContext(options: ResolvedOptions) {
logTree(routeTree, log)
if (dts) {
const content = generateDTS()
let needsServerUpdate = false
if (lastDTS !== content) {
await fs.writeFile(dts, content, 'utf-8')
console.timeLog('writeConfigFiles', 'wrote dts')
lastDTS = content
needsServerUpdate = true
}

const typesConfigContent = generateTypesConfigDTS(MODULE_ROUTES_PATH)
if (lastTypesConfigDTS !== typesConfigContent) {
await fs.writeFile(
dts.replace('.d.ts', '.config.d.ts'),
typesConfigContent,
'utf-8'
)
console.timeLog('writeConfigFiles', 'wrote types config dts')
lastTypesConfigDTS = typesConfigContent
needsServerUpdate = true
}

if (needsServerUpdate) {
// update the files
server?.invalidate(MODULE_ROUTES_PATH)
server?.invalidate(MODULE_VUE_ROUTER)
server?.reload()
Expand Down
4 changes: 2 additions & 2 deletions src/core/moduleConstants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const MODULE_VUE_ROUTER = 'vue-router/auto'
// the path is used by the user and having slashes is just more natural
export const MODULE_ROUTES_PATH = `${MODULE_VUE_ROUTER}/routes`
// vue-router/auto/routes was more natural but didn't work well with TS
export const MODULE_ROUTES_PATH = `${MODULE_VUE_ROUTER}-routes`

export const VIRTUAL_PREFIX = 'virtual:'

Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,11 @@ export default createUnplugin<Options | undefined>((opt = {}, meta) => {
}
}

// we need to use a virtual module so that vite resolves the vue-router/auto/routes
// we need to use a virtual module so that vite resolves the vue-router/auto-routes
// dependency correctly
const resolvedId = getVirtualId(id)

// vue-router/auto/routes
// vue-router/auto-routes
if (resolvedId === MODULE_ROUTES_PATH) {
return ctx.generateRoutes()
}
Expand Down
2 changes: 1 addition & 1 deletion src/type-extensions/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export interface _RouterOptions extends Omit<RouterOptions, 'routes'> {
* Modify the routes before they are passed to the router. You can modify the existing array or return a
* new one.
*
* @param routes - The routes generated by this plugin and exposed by `vue-router/auto/routes`
* @param routes - The routes generated by this plugin and exposed by `vue-router/auto-routes`
*/
extendRoutes?: (routes: RouteRecordRaw[]) => RouteRecordRaw[] | void
}

0 comments on commit 2dc0446

Please sign in to comment.