From 4e538a03e29ed6051407c9340c8215480b1936ac Mon Sep 17 00:00:00 2001 From: anhao <117057608+ah-dc@users.noreply.github.com> Date: Thu, 17 Aug 2023 21:35:28 +0800 Subject: [PATCH] fix(vite): use `''` key for root scope in variable collector (#22679) --- packages/vite/src/plugins/composable-keys.ts | 21 ++++++++++++++----- .../basic/other-composables-folder/local.ts | 5 +++++ .../basic/pages/keyed-composables/local.vue | 8 ++++++- 3 files changed, 28 insertions(+), 6 deletions(-) create mode 100644 test/fixtures/basic/other-composables-folder/local.ts diff --git a/packages/vite/src/plugins/composable-keys.ts b/packages/vite/src/plugins/composable-keys.ts index 43cd18b353..f27c80dbf3 100644 --- a/packages/vite/src/plugins/composable-keys.ts +++ b/packages/vite/src/plugins/composable-keys.ts @@ -141,14 +141,26 @@ export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptio } }) +/* +* track scopes with unique keys. for example +* ```js +* // root scope, marked as '' +* function a () { // '0' +* function b () {} // '0-0' +* function c () {} // '0-1' +* } +* function d () {} // '1' +* // '' +* ``` +* */ class ScopeTracker { + // the top of the stack is not a part of current key, it is used for next level scopeIndexStack: number[] curScopeKey: string constructor () { - // top level this.scopeIndexStack = [0] - this.curScopeKey = '0' + this.curScopeKey = '' } getKey () { @@ -173,8 +185,7 @@ class ScopedVarsCollector { constructor () { this.all = new Map() - // top level - this.curScopeKey = '0' + this.curScopeKey = '' } refresh (scopeKey: string) { @@ -192,7 +203,7 @@ class ScopedVarsCollector { hasVar (scopeKey: string, name: string) { const indices = scopeKey.split('-').map(Number) - for (let i = indices.length; i > 0; i--) { + for (let i = indices.length; i >= 0; i--) { if (this.all.get(indices.slice(0, i).join('-'))?.has(name)) { return true } diff --git a/test/fixtures/basic/other-composables-folder/local.ts b/test/fixtures/basic/other-composables-folder/local.ts new file mode 100644 index 0000000000..46858a2779 --- /dev/null +++ b/test/fixtures/basic/other-composables-folder/local.ts @@ -0,0 +1,5 @@ +function useAsyncData (s?: any) { return s } + +export const ShouldNotBeKeyed = (() => { + return useAsyncData() +})() diff --git a/test/fixtures/basic/pages/keyed-composables/local.vue b/test/fixtures/basic/pages/keyed-composables/local.vue index 7e50cfa7a0..31fdc04af9 100644 --- a/test/fixtures/basic/pages/keyed-composables/local.vue +++ b/test/fixtures/basic/pages/keyed-composables/local.vue @@ -1,4 +1,6 @@