fix(compiler-sfc): automatically infer component name from filename when using script setup (#4997)

close #4993
This commit is contained in:
ygj6
2022-05-10 09:16:28 +08:00
committed by GitHub
parent 7dfe146096
commit 16939241b0
5 changed files with 137 additions and 5 deletions

View File

@@ -1,5 +1,48 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`SFC analyze <script> bindings auto name inference basic 1`] = `
"export default {
name: 'FooBar',
setup(__props, { expose }) {
expose();
const a = 1
return { a }
}
}"
`;
exports[`SFC analyze <script> bindings auto name inference do not overwrite manual name (call) 1`] = `
"import { defineComponent } from 'vue'
const __default__ = defineComponent({
name: 'Baz'
})
export default /*#__PURE__*/Object.assign(__default__, {
setup(__props, { expose }) {
expose();
const a = 1
return { a, defineComponent }
}
})"
`;
exports[`SFC analyze <script> bindings auto name inference do not overwrite manual name (object) 1`] = `
"const __default__ = {
name: 'Baz'
}
export default /*#__PURE__*/Object.assign(__default__, {
setup(__props, { expose }) {
expose();
const a = 1
return { a }
}
})"
`;
exports[`SFC compile <script setup> <script> and <script setup> co-usage script first 1`] = `
"import { x } from './x'

View File

@@ -1550,4 +1550,59 @@ describe('SFC analyze <script> bindings', () => {
foo: BindingTypes.PROPS
})
})
describe('auto name inference', () => {
test('basic', () => {
const { content } = compile(
`<script setup>const a = 1</script>
<template>{{ a }}</template>`,
undefined,
{
filename: 'FooBar.vue'
}
)
expect(content).toMatch(`export default {
name: 'FooBar'`)
assertCode(content)
})
test('do not overwrite manual name (object)', () => {
const { content } = compile(
`<script>
export default {
name: 'Baz'
}
</script>
<script setup>const a = 1</script>
<template>{{ a }}</template>`,
undefined,
{
filename: 'FooBar.vue'
}
)
expect(content).not.toMatch(`name: 'FooBar'`)
expect(content).toMatch(`name: 'Baz'`)
assertCode(content)
})
test('do not overwrite manual name (call)', () => {
const { content } = compile(
`<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: 'Baz'
})
</script>
<script setup>const a = 1</script>
<template>{{ a }}</template>`,
undefined,
{
filename: 'FooBar.vue'
}
)
expect(content).not.toMatch(`name: 'FooBar'`)
expect(content).toMatch(`name: 'Baz'`)
assertCode(content)
})
})
})

View File

@@ -1,13 +1,19 @@
import { parse, SFCScriptCompileOptions, compileScript } from '../src'
import {
parse,
SFCScriptCompileOptions,
compileScript,
SFCParseOptions
} from '../src'
import { parse as babelParse } from '@babel/parser'
export const mockId = 'xxxxxxxx'
export function compileSFCScript(
src: string,
options?: Partial<SFCScriptCompileOptions>
options?: Partial<SFCScriptCompileOptions>,
parseOptions?: SFCParseOptions
) {
const { descriptor } = parse(src)
const { descriptor } = parse(src, parseOptions)
return compileScript(descriptor, {
...options,
id: mockId