Skip to content

Commit

Permalink
refactor(un-jsx): remove ternary inlining
Browse files Browse the repository at this point in the history
  • Loading branch information
pionxzh committed May 7, 2024
1 parent 6726af4 commit 96b034f
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 89 deletions.
64 changes: 0 additions & 64 deletions packages/unminify/src/transformations/__tests__/un-jsx.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,70 +235,6 @@ function fn() {
`,
)

inlineTest('jsx with dynamic Component tag - ternary with constant boolean',
`
function fn() {
return React.createElement(
true ? "a" : "div",
null,
"Hello",
);
}
`,
`
function fn() {
return <div>Hello</div>;
}
`,
)

inlineTest('jsx with dynamic Component tag - ternary with constant boolean in a variable',
`
const Foo = () => {
const r = true;
const g = false;
return jsxs("div", {
children: [
jsx(r ? "a" : "div", { children: "bar" }, "b"),
jsx(g ? "p" : "div", { children: "baz" }, c),
]
});
};
`,
`
const Foo = () => {
return <div><a key="b">bar</a><div key={c}>baz</div></div>;
};
`,
)

inlineTest('jsx with dynamic Component tag - ternary with constant value in a variable',
`
function fn() {
const truthy = "wakaru"
const truthyComp = React.createElement(
truthy ? "a" : "div",
null,
"Hello",
);
const falsy = ""
const falsyComp = React.createElement(
falsy ? "a" : "div",
null,
"Hello",
);
}
`,
`
function fn() {
const truthyComp = <a>Hello</a>;
const falsyComp = <div>Hello</div>;
}
`,
)

inlineTest('jsx with child text that should be wrapped',
`
function fn() {
Expand Down
26 changes: 1 addition & 25 deletions packages/unminify/src/transformations/un-jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,31 +154,7 @@ function toJSX(j: JSCodeshift, path: ASTPath<CallExpression>, pragmas: string[],
tag = j.jsxIdentifier(name)

const variableDeclaration = j.variableDeclaration('const', [j.variableDeclarator(j.identifier(name), type)])
const isVariableDeclaration = root.find(j.VariableDeclarator, {
id: {
type: 'Identifier',
name: variableDeclaration.declarations[0].init?.test?.name,
},
})

// if ternary operator variable value exist
if (isVariableDeclaration.length) {
isVariableDeclaration.forEach((path: any) => {
removeDeclarationIfUnused(j, path, path.node.id.name)
if (path.node.init.value) {
tag = { ...tag, name: variableDeclaration.declarations[0].init.consequent.value }
}
else {
tag = { ...tag, name: variableDeclaration.declarations[0].init.alternate.value }
}
})
}
else {
if (variableDeclaration.declarations[0].init?.alternate?.value) {
tag = { ...tag, name: variableDeclaration.declarations[0].init.alternate.value }
}
}
// insertBefore(j, path, variableDeclaration)
insertBefore(j, path, variableDeclaration)
scope.markAsStale()
}
if (!tag) return null
Expand Down

0 comments on commit 96b034f

Please sign in to comment.