diff --git a/packages/compiler-sfc/__tests__/parse.spec.ts b/packages/compiler-sfc/__tests__/parse.spec.ts index 5f1db5e2499..767dc8fcef9 100644 --- a/packages/compiler-sfc/__tests__/parse.spec.ts +++ b/packages/compiler-sfc/__tests__/parse.spec.ts @@ -320,4 +320,60 @@ h1 { color: red } ) }) }) + + describe('default script lang', () => { + test('default lang for script', () => { + const { descriptor, errors } = parse( + ``, + { + defaultScriptLang: 'ts' + } + ) + expect(errors.length).toBe(0) + expect(descriptor.script?.lang).toBe('ts') + }) + + test('default lang for script setup', () => { + const { descriptor, errors } = parse( + ``, + { + defaultScriptLang: 'ts' + } + ) + expect(errors.length).toBe(0) + expect(descriptor.scriptSetup?.lang).toBe('ts') + }) + + test('default lang for script & script setup', () => { + const { descriptor, errors } = parse( + ` + + + `, + { + defaultScriptLang: 'ts' + } + ) + expect(errors.length).toBe(0) + expect(descriptor.script?.lang).toBe('ts') + expect(descriptor.scriptSetup?.lang).toBe('ts') + }) + + // This only tests if the "source to sfc" cache has "defaultScriptLang" as part of the cache key. + test('source cache key', () => { + // The same SFC as previous test + const { descriptor, errors } = parse( + ` + + + `, + { + defaultScriptLang: 'tsx' + } + ) + expect(errors.length).toBe(0) + expect(descriptor.script?.lang).toBe('tsx') + expect(descriptor.scriptSetup?.lang).toBe('tsx') + }) + }) }) diff --git a/packages/compiler-sfc/src/parse.ts b/packages/compiler-sfc/src/parse.ts index 79065fc667e..c4bde57b39f 100644 --- a/packages/compiler-sfc/src/parse.ts +++ b/packages/compiler-sfc/src/parse.ts @@ -22,6 +22,7 @@ export interface SFCParseOptions { pad?: boolean | 'line' | 'space' ignoreEmpty?: boolean compiler?: TemplateCompiler + defaultScriptLang?: string } export interface SFCBlock { @@ -95,11 +96,18 @@ export function parse( sourceRoot = '', pad = false, ignoreEmpty = true, - compiler = CompilerDOM + compiler = CompilerDOM, + defaultScriptLang }: SFCParseOptions = {} ): SFCParseResult { const sourceKey = - source + sourceMap + filename + sourceRoot + pad + compiler.parse + source + + sourceMap + + filename + + sourceRoot + + pad + + compiler.parse + + (defaultScriptLang ? '@' + defaultScriptLang : '') const cache = sourceToSFC.get(sourceKey) if (cache) { return cache @@ -191,10 +199,12 @@ export function parse( const scriptBlock = createBlock(node, source, pad) as SFCScriptBlock const isSetup = !!scriptBlock.attrs.setup if (isSetup && !descriptor.scriptSetup) { + if (!scriptBlock.lang) scriptBlock.lang = defaultScriptLang descriptor.scriptSetup = scriptBlock break } if (!isSetup && !descriptor.script) { + if (!scriptBlock.lang) scriptBlock.lang = defaultScriptLang descriptor.script = scriptBlock break }