@@ -4,9 +4,11 @@ import { hasPragma, print } from './print';
44import { ASTNode } from './print/nodes' ;
55import { embed , getVisitorKeys } from './embed' ;
66import { snipScriptAndStyleTagContent } from './lib/snipTagContent' ;
7- import { parse } from 'svelte/compiler' ;
7+ import { parse , VERSION } from 'svelte/compiler' ;
88
99const babelParser = prettierPluginBabel . parsers . babel ;
10+ const typescriptParser = prettierPluginBabel . parsers [ 'babel-ts' ] ; // TODO use TypeScript parser in next major?
11+ const isSvelte5Plus = Number ( VERSION . split ( '.' ) [ 0 ] ) >= 5 ;
1012
1113function locStart ( node : any ) {
1214 return node . start ;
@@ -45,14 +47,16 @@ export const parsers: Record<string, Parser> = {
4547 }
4648 } ,
4749 preprocess : ( text , options ) => {
48- text = snipScriptAndStyleTagContent ( text ) ;
49- text = text . trim ( ) ;
50+ const result = snipScriptAndStyleTagContent ( text ) ;
51+ text = result . text . trim ( ) ;
5052 // Prettier sets the preprocessed text as the originalText in case
5153 // the Svelte formatter is called directly. In case it's called
5254 // as an embedded parser (for example when there's a Svelte code block
5355 // inside markdown), the originalText is not updated after preprocessing.
5456 // Therefore we do it ourselves here.
5557 options . originalText = text ;
58+ // Only Svelte 5 can have TS in the template
59+ ( options as any ) . _svelte_ts = isSvelte5Plus && result . isTypescript ;
5660 return text ;
5761 } ,
5862 locStart,
@@ -69,6 +73,19 @@ export const parsers: Record<string, Parser> = {
6973 program = program . expression ;
7074 }
7175
76+ return { ...ast , program } ;
77+ } ,
78+ } ,
79+ svelteTSExpressionParser : {
80+ ...typescriptParser ,
81+ parse : ( text : string , options : any ) => {
82+ const ast = typescriptParser . parse ( text , options ) ;
83+
84+ let program = ast . program . body [ 0 ] ;
85+ if ( ! options . _svelte_asFunction ) {
86+ program = program . expression ;
87+ }
88+
7289 return { ...ast , program } ;
7390 } ,
7491 } ,
0 commit comments