Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(compiler-sfc): fix local var access check for bindings in normal …
…script

fix #4644
  • Loading branch information
yyx990803 committed Sep 22, 2021
1 parent 2476eaa commit 6d6cc90
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
13 changes: 13 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript.spec.ts
Expand Up @@ -1181,6 +1181,19 @@ const emit = defineEmits(['a', 'b'])
defineEmits([bar])
</script>`)
).toThrow(`cannot reference locally declared variables`)

// #4644
expect(() =>
compile(`
<script>const bar = 1</script>
<script setup>
defineProps({
foo: {
default: () => bar
}
})
</script>`)
).not.toThrow(`cannot reference locally declared variables`)
})

test('should allow defineProps/Emit() referencing scope var', () => {
Expand Down
15 changes: 11 additions & 4 deletions packages/compiler-sfc/src/compileScript.ts
Expand Up @@ -239,6 +239,7 @@ export function compileScript(
const helperImports: Set<string> = new Set()
const userImports: Record<string, ImportBinding> = Object.create(null)
const userImportAlias: Record<string, string> = Object.create(null)
const scriptBindings: Record<string, BindingTypes> = Object.create(null)
const setupBindings: Record<string, BindingTypes> = Object.create(null)

let defaultExport: Node | undefined
Expand Down Expand Up @@ -739,15 +740,15 @@ export function compileScript(
}
}
if (node.declaration) {
walkDeclaration(node.declaration, setupBindings, userImportAlias)
walkDeclaration(node.declaration, scriptBindings, userImportAlias)
}
} else if (
(node.type === 'VariableDeclaration' ||
node.type === 'FunctionDeclaration' ||
node.type === 'ClassDeclaration') &&
!node.declare
) {
walkDeclaration(node, setupBindings, userImportAlias)
walkDeclaration(node, scriptBindings, userImportAlias)
}
}

Expand Down Expand Up @@ -1070,6 +1071,9 @@ export function compileScript(
? BindingTypes.SETUP_CONST
: BindingTypes.SETUP_MAYBE_REF
}
for (const key in scriptBindings) {
bindingMetadata[key] = scriptBindings[key]
}
for (const key in setupBindings) {
bindingMetadata[key] = setupBindings[key]
}
Expand Down Expand Up @@ -1198,8 +1202,11 @@ export function compileScript(
returned = `() => {}`
}
} else {
// return bindings from setup
const allBindings: Record<string, any> = { ...setupBindings }
// return bindings from script and script setup
const allBindings: Record<string, any> = {
...scriptBindings,
...setupBindings
}
for (const key in userImports) {
if (!userImports[key].isType && userImports[key].isUsedInTemplate) {
allBindings[key] = true
Expand Down

0 comments on commit 6d6cc90

Please sign in to comment.