diff --git a/packages/babel-traverse/src/path/modification.js b/packages/babel-traverse/src/path/modification.js index 0092a20652..b69f527eed 100644 --- a/packages/babel-traverse/src/path/modification.js +++ b/packages/babel-traverse/src/path/modification.js @@ -107,7 +107,7 @@ export function insertAfter(nodes) { ) { return parentPath.insertAfter(nodes); } else if ( - this.isNodeType("Expression") || + (this.isNodeType("Expression") && !this.isJSXElement()) || (parentPath.isForStatement() && this.key === "init") ) { if (this.node) { diff --git a/packages/babel-traverse/test/modification.js b/packages/babel-traverse/test/modification.js index 0f56fe5f9e..6b08efa0a6 100644 --- a/packages/babel-traverse/test/modification.js +++ b/packages/babel-traverse/test/modification.js @@ -200,6 +200,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.insertAfter( + 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 after", function() { it("the ExportNamedDeclaration", function() { const bodyPath = getPath("export function a() {}", {