2023-03-08 12:17:22 +00:00
|
|
|
import { joinURL } from 'ufo'
|
2023-09-19 21:31:18 +00:00
|
|
|
import type { RouteLocationNormalized } from 'vue-router'
|
2023-10-30 21:05:02 +00:00
|
|
|
import { defineNuxtPlugin, useRuntimeConfig } from '../nuxt'
|
|
|
|
import { useRouter } from '../composables/router'
|
|
|
|
import { reloadNuxtApp } from '../composables/chunk'
|
2023-02-16 12:43:58 +00:00
|
|
|
|
2023-04-11 11:58:43 +00:00
|
|
|
export default defineNuxtPlugin({
|
|
|
|
name: 'nuxt:chunk-reload',
|
|
|
|
setup (nuxtApp) {
|
|
|
|
const router = useRouter()
|
|
|
|
const config = useRuntimeConfig()
|
2023-02-16 12:43:58 +00:00
|
|
|
|
2023-04-11 11:58:43 +00:00
|
|
|
const chunkErrors = new Set()
|
2023-02-16 12:43:58 +00:00
|
|
|
|
2023-04-11 11:58:43 +00:00
|
|
|
router.beforeEach(() => { chunkErrors.clear() })
|
|
|
|
nuxtApp.hook('app:chunkError', ({ error }) => { chunkErrors.add(error) })
|
2023-02-16 12:43:58 +00:00
|
|
|
|
2023-09-19 21:31:18 +00:00
|
|
|
function reloadAppAtPath (to: RouteLocationNormalized) {
|
|
|
|
const isHash = 'href' in to && (to.href as string).startsWith('#')
|
|
|
|
const path = isHash ? config.app.baseURL + (to as any).href : joinURL(config.app.baseURL, to.fullPath)
|
|
|
|
reloadNuxtApp({ path, persistState: true })
|
|
|
|
}
|
|
|
|
|
|
|
|
nuxtApp.hook('app:manifest:update', () => {
|
|
|
|
router.beforeResolve(reloadAppAtPath)
|
|
|
|
})
|
|
|
|
|
2023-04-11 11:58:43 +00:00
|
|
|
router.onError((error, to) => {
|
|
|
|
if (chunkErrors.has(error)) {
|
2023-09-19 21:31:18 +00:00
|
|
|
reloadAppAtPath(to)
|
2023-04-11 11:58:43 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2023-02-16 12:43:58 +00:00
|
|
|
})
|