diff --git a/src/client/utils/__tests__/compileCode.spec.ts b/src/client/utils/__tests__/compileCode.spec.ts
index 84c2f64a2..d6a19df9b 100644
--- a/src/client/utils/__tests__/compileCode.spec.ts
+++ b/src/client/utils/__tests__/compileCode.spec.ts
@@ -51,18 +51,16 @@ React.createElement( Button, null )"
`);
});
- test('wrap JSX in Fragment', () => {
- const result = compileCode(
- `
-
-
`,
- compilerConfig
+ test('wrap JSX in Fragment if adjacent on line 1', () => {
+ const result = compileCode(``, compilerConfig);
+ expect(result).toMatchInlineSnapshot(
+ `"React.createElement( React.Fragment, null, React.createElement( 'span', null ), React.createElement( 'span', null ) );"`
);
- expect(result).toMatchInlineSnapshot(`
-"React.createElement( React.Fragment, null, React.createElement( 'div', null,
- React.createElement( 'button', null, \\"Click\\" )
-) );"
-`);
+ });
+
+ test('don’t wrap JSX in Fragment if there is only one statement', () => {
+ const result = compileCode(`;`, compilerConfig);
+ expect(result).toMatchInlineSnapshot(`"React.createElement( Button, null );"`);
});
test('don’t wrap JSX in Fragment if it’s in the middle', () => {
diff --git a/src/client/utils/compileCode.ts b/src/client/utils/compileCode.ts
index 083b0206f..236f13f1e 100644
--- a/src/client/utils/compileCode.ts
+++ b/src/client/utils/compileCode.ts
@@ -18,9 +18,23 @@ export default function compileCode(
onError?: (err: Error) => void
): string {
try {
- const wrappedCode = startsWithJsx(code) ? wrapCodeInFragment(code) : code;
- const compiledCode = compile(wrappedCode, compilerConfig);
- return transpileImports(compiledCode);
+ let compiledCode;
+
+ try {
+ compiledCode = compile(code, compilerConfig);
+ } catch (err) {
+ if (
+ err instanceof SyntaxError &&
+ err.message.startsWith('Adjacent JSX elements must be wrapped in an enclosing tag')
+ ) {
+ const wrappedCode = startsWithJsx(code) ? wrapCodeInFragment(code) : code;
+ compiledCode = compile(wrappedCode, compilerConfig);
+ } else if (onError && err instanceof Error) {
+ onError(err);
+ }
+ }
+
+ return compiledCode ? transpileImports(compiledCode) : '';
} catch (err) {
if (onError && err instanceof Error) {
onError(err);