diff --git a/src/babel/traversal/path/index.js b/src/babel/traversal/path/index.js index bf9dd5688f..a70575bee4 100644 --- a/src/babel/traversal/path/index.js +++ b/src/babel/traversal/path/index.js @@ -361,12 +361,44 @@ export default class TraversalPath { if (log) file.log.debug("End scope building"); } - _remove() { - if (Array.isArray(this.container)) { - this.container.splice(this.key, 1); - this.updateSiblingKeys(this.key, -1); + /** + * Share comments amongst siblings. + */ + + shareCommentsWithSiblings() { + var node = this.node; + if (!node) return; + + var trailing = node.trailingComments; + var leading = node.leadingComments; + if (!trailing && !leading) return; + + var prev = this.getSibling(this.key - 1); + var next = this.getSibling(this.key + 1); + + if (!prev.node) prev = next; + if (!next.node) next = prev; + + prev.giveComments("trailing", leading); + next.giveComments("leading", trailing); + } + + /** + * Give node `comments` of the specified `type`. + */ + + giveComments(type: string, comments: Array) { + if (!comments) return; + + var node = this.node; + if (!node) return; + + var key = `${type}Comments`; + + if (node[key]) { + node[key] = node[key].concat(comments); } else { - this.container[this.key] = null; + node[key] = comments; } } @@ -375,6 +407,7 @@ export default class TraversalPath { */ remove() { + this.shareCommentsWithSiblings(); this._remove(); this.removed = true; @@ -409,6 +442,15 @@ export default class TraversalPath { } } + _remove() { + if (Array.isArray(this.container)) { + this.container.splice(this.key, 1); + this.updateSiblingKeys(this.key, -1); + } else { + this.container[this.key] = null; + } + } + /** * Description */ diff --git a/test/core/fixtures/transformation/flow/type-comments/expected.js b/test/core/fixtures/transformation/flow/type-comments/expected.js index fc9059820d..84dea6f757 100644 --- a/test/core/fixtures/transformation/flow/type-comments/expected.js +++ b/test/core/fixtures/transformation/flow/type-comments/expected.js @@ -1,3 +1,4 @@ var x = 1; // comment 1 + var y = 2;