Skip to content

feat(compiler-sfc): withDefaults supports the use of local variables #8592

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,27 @@ return { props, get defaults() { return defaults } }
})"
`;

exports[`defineProps > withDefaults (locally variable) 1`] = `
"import { mergeDefaults as _mergeDefaults, defineComponent as _defineComponent } from 'vue'
const defaults = { baz: false }

export default /*#__PURE__*/_defineComponent({
props: _mergeDefaults({
baz: { type: Boolean, required: true }
}, defaults),
setup(__props: any, { expose: __expose }) {
__expose();

const props = __props;



return { defaults, props }
}

})"
`;

exports[`defineProps > withDefaults (reference) 1`] = `
"import { mergeDefaults as _mergeDefaults, defineComponent as _defineComponent } from 'vue'
import { defaults } from './foo'
Expand Down
34 changes: 34 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript/defineProps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,26 @@ const props = defineProps({ foo: String })
)
})

test('withDefaults (locally variable)', () => {
const { content } = compile(`
<script setup lang="ts">
const defaults = { baz: false }
const props = withDefaults(defineProps<{
baz: boolean
}>(), defaults)
</script>
`)

assertCode(content)
expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
expect(content).toMatch(
`
_mergeDefaults({
baz: { type: Boolean, required: true }
}, defaults)`.trim()
)
})

// #7111
test('withDefaults (dynamic) w/ production mode', () => {
const { content } = compile(
Expand Down Expand Up @@ -607,5 +627,19 @@ const props = defineProps({ foo: String })
</script>`)
}).toThrow(`cannot accept both type and non-type arguments`)
})

test('withDefaults (locally variable)', () => {
expect(() => {
compile(`
<script setup lang="ts">
const defaults = { bar: 1 }
withDefaults(defineProps<{
bar?: number
}>(), defaults)
defaults.bar++
</script>
`)
}).toThrow(`cannot reference locally declared variables`)
})
})
})
44 changes: 43 additions & 1 deletion packages/compiler-sfc/src/compileScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,13 @@ export function compileScript(
// const ctx.bindingMetadata: BindingMetadata = {}
const scriptBindings: Record<string, BindingTypes> = Object.create(null)
const setupBindings: Record<string, BindingTypes> = Object.create(null)
const withDefaultsVariables: Record<
string,
{
node: Statement
needHoist?: boolean
}
> = {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
> = {}
> = Object.create(null)


let defaultExport: Node | undefined
let hasAwait = false
Expand Down Expand Up @@ -258,7 +265,11 @@ export function compileScript(
if (!node) return
walkIdentifiers(node, id => {
const binding = setupBindings[id.name]
if (binding && binding !== BindingTypes.LITERAL_CONST) {
if (
binding &&
binding !== BindingTypes.LITERAL_CONST &&
!withDefaultsVariables[id.name].needHoist
) {
ctx.error(
`\`${method}()\` in <script setup> cannot reference locally ` +
`declared variables because it will be hoisted outside of the ` +
Expand Down Expand Up @@ -636,6 +647,30 @@ export function compileScript(
parent!.type === 'ExpressionStatement'
)
}

if (child.type === 'Identifier') {
if (parent!.type === 'VariableDeclarator') {
withDefaultsVariables[child.name] = {
node
}
} else if (
parent!.type === 'CallExpression' &&
parent.callee.type === 'Identifier' &&
parent.callee.name === WITH_DEFAULTS &&
withDefaultsVariables[child.name]
) {
const variable = withDefaultsVariables[child.name]
if (variable.needHoist !== false) {
variable.needHoist = true
}
} else if (
parent!.type !== 'VariableDeclaration' &&
withDefaultsVariables[child.name]
) {
const variable = withDefaultsVariables[child.name]
variable.needHoist = false
}
}
},
exit(node: Node) {
if (node.type === 'BlockStatement') scope.pop()
Expand Down Expand Up @@ -671,6 +706,13 @@ export function compileScript(
}
}

for (const key in withDefaultsVariables) {
const variable = withDefaultsVariables[key]
if (variable.needHoist) {
hoistNode(variable.node)
}
}

// 3 props destructure transform
if (ctx.propsDestructureDecl) {
transformDestructuredProps(ctx, vueImportAliases)
Expand Down