Skip to content

Commit 4b2bfa8

Browse files
committed
feat(warn): warn if component is a promise
1 parent 5c8cd6e commit 4b2bfa8

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

__tests__/warnings.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,4 +163,15 @@ describe('warnings', () => {
163163
'duplicated params with name "id" for path "/:id/:id"'
164164
).toHaveBeenWarned()
165165
})
166+
167+
it('warns if component is a promise instead of a function that returns a promise', async () => {
168+
const router = createRouter({
169+
history: createMemoryHistory(),
170+
// simulates import('./component.vue')
171+
routes: [{ path: '/foo', component: Promise.resolve(component) }],
172+
})
173+
174+
await expect(router.push({ path: '/foo' })).resolves.toBe(undefined)
175+
expect('"/foo" is a Promise instead of a function').toHaveBeenWarned()
176+
})
166177
})

src/navigationGuards.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,16 @@ export function extractComponentsGuards(
166166

167167
for (const record of matched) {
168168
for (const name in record.components) {
169-
const rawComponent = record.components[name]
169+
let rawComponent = record.components[name]
170+
// warn if user wrote import('/component.vue') instead of () => import('./component.vue')
171+
if (__DEV__ && 'then' in rawComponent) {
172+
warn(
173+
`Component "${name}" in record with path "${record.path}" is a Promise instead of a function that returns a Promise. Did you write "import('./MyPage.vue')" instead of "() => import('./MyPage.vue')"? This will break in production if not fixed.`
174+
)
175+
let promise = rawComponent
176+
rawComponent = () => promise
177+
}
178+
170179
if (isRouteComponent(rawComponent)) {
171180
// __vccOpts is added by vue-class-component and contain the regular options
172181
let options: ComponentOptions =
@@ -182,7 +191,7 @@ export function extractComponentsGuards(
182191

183192
if (__DEV__ && !('catch' in componentPromise)) {
184193
warn(
185-
`Component "${name}" at record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`
194+
`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`
186195
)
187196
componentPromise = Promise.resolve(componentPromise as RouteComponent)
188197
} else {

0 commit comments

Comments
 (0)