diff --git a/packages/babel-traverse/src/path/modification.js b/packages/babel-traverse/src/path/modification.js index add972ee4327..abd1890e993e 100644 --- a/packages/babel-traverse/src/path/modification.js +++ b/packages/babel-traverse/src/path/modification.js @@ -26,7 +26,8 @@ export function insertBefore(nodes) { } else if ( (this.isNodeType("Expression") && this.listKey !== "params" && - this.listKey !== "arguments") || + this.listKey !== "arguments" && + !this.isJSXElement()) || (parentPath.isForStatement() && this.key === "init") ) { if (this.node) nodes.push(this.node); diff --git a/packages/babel-traverse/test/modification.js b/packages/babel-traverse/test/modification.js index ad5d40c69a8a..027b71945723 100644 --- a/packages/babel-traverse/test/modification.js +++ b/packages/babel-traverse/test/modification.js @@ -116,6 +116,32 @@ describe("modification", function() { ); }); + it("returns inserted path with nested JSXElement", function() { + const ast = parse("
foo
", { + plugins: ["jsx"], + }); + let path; + traverse(ast, { + Program: function(_path) { + path = _path.get("body.0"); + }, + JSXElement: function(path) { + const tagName = path.node.openingElement.name.name; + if (tagName !== "span") return; + path.insertBefore( + t.JSXElement( + t.JSXOpeningElement(t.JSXIdentifier("div"), [], false), + t.JSXClosingElement(t.JSXIdentifier("div")), + [], + ), + ); + }, + }); + expect(generateCode(path)).toBe( + "
foo
;", + ); + }); + describe("when the parent is an export declaration inserts the node before", function() { it("the ExportNamedDeclaration", function() { const bodyPath = getPath("export function a() {}", {