diff --git a/packages/vite/src/node/plugins/importAnalysis.ts b/packages/vite/src/node/plugins/importAnalysis.ts index 40f760f062a462..3d3f81564a30e7 100644 --- a/packages/vite/src/node/plugins/importAnalysis.ts +++ b/packages/vite/src/node/plugins/importAnalysis.ts @@ -406,19 +406,20 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { const prop = source.slice(end, end + 4) if (prop === '.hot') { hasHMR = true - if (source.slice(end + 4, end + 11) === '.accept') { + const endHot = end + 4 + (source[end + 4] === '?' ? 1 : 0) + if (source.slice(endHot, endHot + 7) === '.accept') { // further analyze accepted modules - if (source.slice(end + 4, end + 18) === '.acceptExports') { + if (source.slice(endHot, endHot + 14) === '.acceptExports') { lexAcceptedHmrExports( source, - source.indexOf('(', end + 18) + 1, + source.indexOf('(', endHot + 14) + 1, acceptedExports, ) isPartiallySelfAccepting = true } else if ( lexAcceptedHmrDeps( source, - source.indexOf('(', end + 11) + 1, + source.indexOf('(', endHot + 7) + 1, acceptedUrls, ) ) { diff --git a/playground/hmr/__tests__/hmr.spec.ts b/playground/hmr/__tests__/hmr.spec.ts index b6c786efefba54..a7fbbad80ae90e 100644 --- a/playground/hmr/__tests__/hmr.spec.ts +++ b/playground/hmr/__tests__/hmr.spec.ts @@ -774,4 +774,16 @@ if (import.meta.hot) { 'parent:child', ) }) + + test('import.meta.hot?.accept', async () => { + const el = await page.$('.optional-chaining') + await untilBrowserLogAfter( + () => + editFile('optional-chaining/child.js', (code) => + code.replace('const foo = 1', 'const foo = 2'), + ), + '(optional-chaining) child update', + ) + await untilUpdated(() => el.textContent(), '2') + }) } diff --git a/playground/hmr/hmr.ts b/playground/hmr/hmr.ts index b4b23a949da783..9748fdd1e8bc11 100644 --- a/playground/hmr/hmr.ts +++ b/playground/hmr/hmr.ts @@ -3,6 +3,7 @@ import { foo as depFoo, nestedFoo } from './hmrDep' import './importing-updated' import './invalidation/parent' import './file-delete-restore' +import './optional-chaining/parent' export const foo = 1 text('.app', foo) diff --git a/playground/hmr/index.html b/playground/hmr/index.html index 9aadeaae6f3ff8..34d8eb631232a5 100644 --- a/playground/hmr/index.html +++ b/playground/hmr/index.html @@ -31,3 +31,4 @@
+
diff --git a/playground/hmr/optional-chaining/child.js b/playground/hmr/optional-chaining/child.js new file mode 100644 index 00000000000000..766766a6260612 --- /dev/null +++ b/playground/hmr/optional-chaining/child.js @@ -0,0 +1 @@ +export const foo = 1 diff --git a/playground/hmr/optional-chaining/parent.js b/playground/hmr/optional-chaining/parent.js new file mode 100644 index 00000000000000..4afe3ce71c8dc8 --- /dev/null +++ b/playground/hmr/optional-chaining/parent.js @@ -0,0 +1,6 @@ +import { foo } from './child' + +import.meta.hot?.accept('./child', ({ foo }) => { + console.log('(optional-chaining) child update') + document.querySelector('.optional-chaining').textContent = foo +})