Skip to content

fix: prevent unnecessary wrapping of single line jsx elements #2183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions src/client/utils/__tests__/compileCode.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,16 @@ React.createElement( Button, null )"
`);
});

test('wrap JSX in Fragment', () => {
const result = compileCode(
`<div>
<button>Click</button>
</div>`,
compilerConfig
test('wrap JSX in Fragment if adjacent on line 1', () => {
const result = compileCode(`<span /><span />`, 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(`<Button />;`, compilerConfig);
expect(result).toMatchInlineSnapshot(`"React.createElement( Button, null );"`);
});

test('don’t wrap JSX in Fragment if it’s in the middle', () => {
Expand Down
20 changes: 17 additions & 3 deletions src/client/utils/compileCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading