Skip to content

Commit

Permalink
feat(warn): warn if component is a promise
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed May 24, 2020
1 parent 5c8cd6e commit 4b2bfa8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
11 changes: 11 additions & 0 deletions __tests__/warnings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,15 @@ describe('warnings', () => {
'duplicated params with name "id" for path "/:id/:id"'
).toHaveBeenWarned()
})

it('warns if component is a promise instead of a function that returns a promise', async () => {
const router = createRouter({
history: createMemoryHistory(),
// simulates import('./component.vue')
routes: [{ path: '/foo', component: Promise.resolve(component) }],
})

await expect(router.push({ path: '/foo' })).resolves.toBe(undefined)
expect('"/foo" is a Promise instead of a function').toHaveBeenWarned()
})
})
13 changes: 11 additions & 2 deletions src/navigationGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,16 @@ export function extractComponentsGuards(

for (const record of matched) {
for (const name in record.components) {
const rawComponent = record.components[name]
let rawComponent = record.components[name]
// warn if user wrote import('/component.vue') instead of () => import('./component.vue')
if (__DEV__ && 'then' in rawComponent) {
warn(
`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.`
)
let promise = rawComponent
rawComponent = () => promise
}

if (isRouteComponent(rawComponent)) {
// __vccOpts is added by vue-class-component and contain the regular options
let options: ComponentOptions =
Expand All @@ -182,7 +191,7 @@ export function extractComponentsGuards(

if (__DEV__ && !('catch' in componentPromise)) {
warn(
`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.`
`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.`
)
componentPromise = Promise.resolve(componentPromise as RouteComponent)
} else {
Expand Down

0 comments on commit 4b2bfa8

Please sign in to comment.