Skip to content

Commit 25e787d

Browse files
authored
Implement JSXFragment (#200)
* Implement JSXFragment * Add `Fragment` to generated header * Only add JSX Fragment when it was encountered
1 parent c1b1816 commit 25e787d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src-transpiler/Stringifier.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,13 +228,17 @@ class Stringifier {
228228
}
229229
return out;
230230
}
231+
encounteredFragment = false;
231232
/**
232233
* @returns {string} The header.
233234
*/
234235
getHeader() {
235236
if (!this.addReactImport) {
236237
return '';
237238
}
239+
if (this.encounteredFragment) {
240+
return "import {createElement, Fragment} from 'react';\n";
241+
}
238242
return "import {createElement} from 'react';\n";
239243
}
240244
get parent() {
@@ -1133,6 +1137,42 @@ class Stringifier {
11331137
out += ')';
11341138
return out;
11351139
}
1140+
/**
1141+
* @param {import("@babel/types").JSXFragment} node - The Babel AST node.
1142+
* @returns {string} Stringification of the node.
1143+
*/
1144+
JSXFragment(node) {
1145+
const {/*openingFragment, closingFragment,*/ children} = node;
1146+
this.encounteredFragment = true;
1147+
// console.log('JSXFragment', {openingFragment, closingFragment, children});
1148+
let {spaces} = this;
1149+
let out = 'createElement(\n';
1150+
this.numSpaces++;
1151+
spaces = this.spaces;
1152+
out += spaces;
1153+
out += 'Fragment,\n';
1154+
out += spaces;
1155+
out += 'null';
1156+
// Same code for children as in JSXElement
1157+
if (children.length) {
1158+
out += ',\n';
1159+
for (const child of children) {
1160+
const source = this.toSource(child);
1161+
if (!source.length) {
1162+
continue;
1163+
}
1164+
out += spaces;
1165+
out += source;
1166+
out += ',\n';
1167+
}
1168+
} else {
1169+
out += '\n';
1170+
}
1171+
this.numSpaces--;
1172+
out += this.spaces;
1173+
out += ')';
1174+
return out;
1175+
}
11361176
/**
11371177
* @param {import("@babel/types").JSXIdentifier} node - The Babel AST node.
11381178
* @returns {string} Stringification of the node.

0 commit comments

Comments
 (0)