2023-02-16 12:43:58 +00:00
|
|
|
import MagicString from 'magic-string'
|
|
|
|
import type { Plugin } from 'vite'
|
|
|
|
|
2023-09-15 12:16:09 +00:00
|
|
|
const vitePreloadHelperId = '\0vite/preload-helper'
|
|
|
|
|
|
|
|
// TODO: remove this function when we upgrade to vite 5
|
2023-02-16 12:43:58 +00:00
|
|
|
export function chunkErrorPlugin (options: { sourcemap?: boolean }): Plugin {
|
|
|
|
return {
|
|
|
|
name: 'nuxt:chunk-error',
|
|
|
|
transform (code, id) {
|
2023-09-15 12:16:09 +00:00
|
|
|
// Vite 5 has an id with extension
|
|
|
|
if (!(id === vitePreloadHelperId || id === `${vitePreloadHelperId}.js`) || code.includes('nuxt.preloadError')) { return }
|
2023-02-16 12:43:58 +00:00
|
|
|
|
|
|
|
const s = new MagicString(code)
|
|
|
|
s.replace(/__vitePreload/g, '___vitePreload')
|
|
|
|
s.append(`
|
|
|
|
export const __vitePreload = (...args) => ___vitePreload(...args).catch(err => {
|
|
|
|
const e = new Event("nuxt.preloadError");
|
|
|
|
e.payload = err;
|
|
|
|
window.dispatchEvent(e);
|
|
|
|
throw err;
|
|
|
|
})`)
|
|
|
|
|
|
|
|
return {
|
|
|
|
code: s.toString(),
|
|
|
|
map: options.sourcemap
|
2023-04-14 17:21:08 +00:00
|
|
|
? s.generateMap({ hires: true })
|
2023-02-16 12:43:58 +00:00
|
|
|
: undefined
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|