diff --git a/src/index.js b/src/index.js index 77e9b4c..98c8340 100644 --- a/src/index.js +++ b/src/index.js @@ -552,6 +552,11 @@ export default function (babel) { if (t.isBlockStatement(path.node[key])) { path.get(key).canSwapBetweenExpressionAndStatement = () => true; path.get(key).replaceExpressionWithStatements(path.node[key].body); + return path.node[key]; + } else if (t.isExpressionStatement(path.node[key])) { + return path.node[key].expression; + } else { + return path.node[key]; } } @@ -838,11 +843,11 @@ export default function (babel) { validate: assertNodeType("Expression") }, consequent: { - validate: assertNodeType("Expression", "BlockStatement") + validate: assertNodeType("Expression", "BlockStatement", "ExpressionStatement") }, alternate: { optional: true, - validate: assertNodeType("Expression", "BlockStatement") + validate: assertNodeType("Expression", "BlockStatement", "ExpressionStatement") } } }); @@ -1128,15 +1133,16 @@ export default function (babel) { }, IfExpression(path) { - blockToExpression(path, "consequent"); + const consequent = blockToExpression(path, "consequent"); + let alternate; if (path.node.alternate) { - blockToExpression(path, "alternate"); + alternate = blockToExpression(path, "alternate"); } else { - path.get("alternate").replaceWith(t.nullLiteral()); + alternate = t.nullLiteral(); } - path.replaceWith(t.conditionalExpression(path.node.test, path.node.consequent, path.node.alternate)); + path.replaceWith(t.conditionalExpression(path.node.test, consequent, alternate)); }, AssignmentExpression(path) { diff --git a/test/fixtures/if-expressions/js-style/actual.js b/test/fixtures/if-expressions/js-style/actual.js new file mode 100644 index 0000000..d92f63c --- /dev/null +++ b/test/fixtures/if-expressions/js-style/actual.js @@ -0,0 +1,3 @@ +x = if true {1} else 2 + +y = if(false) 2 else 3 diff --git a/test/fixtures/if-expressions/js-style/exec.js b/test/fixtures/if-expressions/js-style/exec.js new file mode 100644 index 0000000..131d33e --- /dev/null +++ b/test/fixtures/if-expressions/js-style/exec.js @@ -0,0 +1,8 @@ +x = if true {2} else 3 +assert(x == 2, "2") + +y = if (false) 4 else {5} +assert(y == 5, "5") + +z = if (true) 6 else 7 +assert(z == 6, "6") diff --git a/test/fixtures/if-expressions/js-style/expected.js b/test/fixtures/if-expressions/js-style/expected.js new file mode 100644 index 0000000..3eb2fee --- /dev/null +++ b/test/fixtures/if-expressions/js-style/expected.js @@ -0,0 +1,3 @@ +const x = true ? 1 : 2; + +const y = false ? 2 : 3; \ No newline at end of file