@@ -40,7 +40,8 @@ import type { } from 'mdast-util-mdx'; // Type-only empty import to register MDX
40
40
import assert from 'node:assert/strict'
41
41
import * as path from 'node:path'
42
42
import * as prettier from 'prettier'
43
- import tsBlankSpace from 'ts-blank-space'
43
+ import { blankSourceFile } from 'ts-blank-space'
44
+ import * as ts from 'typescript'
44
45
import type { Plugin } from 'unified'
45
46
import { visitParents } from 'unist-util-visit-parents'
46
47
@@ -138,7 +139,8 @@ async function makeJsCodeBlock(
138
139
) } `
139
140
)
140
141
const lang = node . lang ?. replace ( 'ts' , 'js' )
141
- const code = await format ( tsBlankSpace ( node . value ) , {
142
+ const isJsx = node . lang . endsWith ( 'x' )
143
+ const code = await format ( convertToJs ( node . value , { jsx : isJsx } ) , {
142
144
parser : 'babel' ,
143
145
location,
144
146
} )
@@ -167,6 +169,22 @@ async function makeTsCodeBlock(
167
169
}
168
170
}
169
171
172
+ function convertToJs ( code : string , { jsx } : { jsx : boolean } ) {
173
+ // We create a source file from ts so that way we can specify if
174
+ // we want to use JSX or not, because the parsing is different.
175
+ // Copied from the ts-blank-space playground
176
+ // https://github.com/bloomberg/ts-blank-space/blob/4102b1f26b1c53d38a1de74c10f262af5fd34fe8/website/play/play-utils.ts#L4
177
+ const sourceFile = ts . createSourceFile (
178
+ 'input.ts' ,
179
+ code ,
180
+ { languageVersion : ts . ScriptTarget . ESNext } ,
181
+ true ,
182
+ jsx ? ts . ScriptKind . TSX : ts . ScriptKind . TS
183
+ )
184
+
185
+ return blankSourceFile ( sourceFile )
186
+ }
187
+
170
188
async function format (
171
189
code : string ,
172
190
{ parser, location } : { parser : prettier . Options [ 'parser' ] ; location : string }
0 commit comments