From 116e37acf1a9ce808bc7a7f3a1439ab749c168e3 Mon Sep 17 00:00:00 2001 From: btea <2356281422@qq.com> Date: Tue, 30 Jul 2024 13:13:02 +0800 Subject: [PATCH] feat(types): support custom VitePreloadErrorEvent (#17615) --- packages/vite/client.d.ts | 17 +++++++++++++++++ .../src/node/plugins/importAnalysisBuild.ts | 7 +++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/vite/client.d.ts b/packages/vite/client.d.ts index 28cce42cba87d6..d67cf70c632503 100644 --- a/packages/vite/client.d.ts +++ b/packages/vite/client.d.ts @@ -246,3 +246,20 @@ declare module '*?inline' { const src: string export default src } + +declare interface VitePreloadErrorEvent extends Event { + payload: Error +} + +declare interface Window { + addEventListener( + type: 'vite:preloadError', + listener: (this: Window, ev: VitePreloadErrorEvent) => unknown, + options?: boolean | AddEventListenerOptions, + ): void + removeEventListener( + type: 'vite:preloadError', + listener: (this: Window, ev: VitePreloadErrorEvent) => unknown, + options?: boolean | EventListenerOptions, + ): void +} diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index bfbe0d69106eda..7dcad179654fe4 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -26,6 +26,8 @@ type FileDep = { runtime: boolean } +type VitePreloadErrorEvent = Event & { payload: Error } + /** * A flag for injected helpers. This flag will be set to `false` if the output * target is not native es - so that injected helper logic can be conditionally @@ -145,8 +147,9 @@ function preload( return promise .then(() => baseModule()) .catch((err) => { - const e = new Event('vite:preloadError', { cancelable: true }) - // @ts-expect-error custom payload + const e = new Event('vite:preloadError', { + cancelable: true, + }) as VitePreloadErrorEvent e.payload = err window.dispatchEvent(e) if (!e.defaultPrevented) {