Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Commit

Permalink
feat(pages): routes HMR
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu authored and danielroe committed Nov 15, 2022
1 parent f7f0a95 commit ba31e9e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
12 changes: 11 additions & 1 deletion packages/nuxt/src/pages/module.ts
Expand Up @@ -167,7 +167,17 @@ export default defineNuxtModule({
const pages = await resolvePagesRoutes()
await nuxt.callHook('pages:extend', pages)
const { routes, imports } = normalizeRoutes(pages)
return [...imports, `export default ${routes}`].join('\n')
return [
...imports,
`export default ${routes}`,
'export function onUpdate(fn) { onUpdate._fn = fn }',
'if (import.meta.hot) {',
' import.meta.hot.accept((mod) => {',
' onUpdate._fn?.(mod.default)',
' mod.onUpdate._fn = onUpdate._fn',
' })',
'}'
].join('\n')
}
})

Expand Down
15 changes: 14 additions & 1 deletion packages/nuxt/src/pages/runtime/router.ts
Expand Up @@ -67,10 +67,23 @@ export default defineNuxtPlugin(async (nuxtApp) => {
const router = createRouter({
...routerOptions,
history,
routes
routes: []
})
let clearRoutes = router.addRoute({ path: '', children: routes })
nuxtApp.vueApp.use(router)

// Routes HMR
if (import.meta.hot) {
// @ts-expect-error
import('#build/routes').then(({ onUpdate }) => {
onUpdate((newRoutes: any) => {
const routes = routerOptions.routes?.(newRoutes) ?? newRoutes
clearRoutes()
clearRoutes = router.addRoute({ path: '', children: routes })
})
})
}

const previousRoute = shallowRef(router.currentRoute.value)
router.afterEach((_to, from) => {
previousRoute.value = from
Expand Down

0 comments on commit ba31e9e

Please sign in to comment.