From 71901b3161540bc4248c241c412c4fb836e20a9a Mon Sep 17 00:00:00 2001 From: daiwei Date: Fri, 8 Nov 2024 22:32:20 +0800 Subject: [PATCH 1/4] fix(HMR): hmr reload if relies file changed --- packages/plugin-vue/src/index.ts | 6 ++++++ packages/plugin-vue/src/main.ts | 12 +++++++++++- playground/vue/Hmr.vue | 3 +++ playground/vue/__tests__/vue.spec.ts | 11 +++++++++++ playground/vue/lib.js | 3 +++ 5 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 playground/vue/lib.js diff --git a/packages/plugin-vue/src/index.ts b/packages/plugin-vue/src/index.ts index 2ac6d5b8..a38ca355 100644 --- a/packages/plugin-vue/src/index.ts +++ b/packages/plugin-vue/src/index.ts @@ -200,6 +200,12 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin { }, handleHotUpdate(ctx) { + ctx.server.ws.send({ + type: 'custom', + event: 'file-changed', + data: { file: ctx.file }, + }) + if (options.value.compiler.invalidateTypeCache) { options.value.compiler.invalidateTypeCache(ctx.file) } diff --git a/packages/plugin-vue/src/main.ts b/packages/plugin-vue/src/main.ts index fce8c8ea..a039f179 100644 --- a/packages/plugin-vue/src/main.ts +++ b/packages/plugin-vue/src/main.ts @@ -148,9 +148,19 @@ export async function transformMain( `typeof __VUE_HMR_RUNTIME__ !== 'undefined' && ` + `__VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)`, ) + output.push( + `import.meta.hot.on('file-changed', ({ file }) => {`, + ` window.__VUE_HMR_CHANGED_FILE = file`, + `})`, + ) // check if the template is the only thing that changed if (prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) { - output.push(`export const _rerender_only = true`) + // #7 vite will cache the transform result. If the current hot update + // is triggered by changes in other files that the current component + // relies on, a reload is required. + output.push( + `export const _rerender_only = window.__VUE_HMR_CHANGED_FILE === ${JSON.stringify(filename)}`, + ) } output.push( `import.meta.hot.accept(mod => {`, diff --git a/playground/vue/Hmr.vue b/playground/vue/Hmr.vue index 5535467a..541929d4 100644 --- a/playground/vue/Hmr.vue +++ b/playground/vue/Hmr.vue @@ -2,11 +2,14 @@

HMR

Click the button then edit this message. The count should be preserved.

+ {{ number }}