Skip to content

Commit c9d54e2

Browse files
committed
Correctly parse JSX
1 parent 2bc974e commit c9d54e2

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

web/src/remark/auto-js-code.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ import type { } from 'mdast-util-mdx'; // Type-only empty import to register MDX
4040
import assert from 'node:assert/strict'
4141
import * as path from 'node:path'
4242
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'
4445
import type { Plugin } from 'unified'
4546
import { visitParents } from 'unist-util-visit-parents'
4647

@@ -138,7 +139,8 @@ async function makeJsCodeBlock(
138139
)}`
139140
)
140141
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 }), {
142144
parser: 'babel',
143145
location,
144146
})
@@ -167,6 +169,22 @@ async function makeTsCodeBlock(
167169
}
168170
}
169171

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+
170188
async function format(
171189
code: string,
172190
{ parser, location }: { parser: prettier.Options['parser']; location: string }

0 commit comments

Comments
 (0)