diff --git a/src/arborist.js b/src/arborist.js index ef07b3d..dfd2a06 100644 --- a/src/arborist.js +++ b/src/arborist.js @@ -85,8 +85,8 @@ const Arborist = class { const leadingComments = rootNode.leadingComments || []; const trailingComments = rootNode.trailingComments || []; rootNode = rootNodeReplacement[1]; - if (leadingComments.length) rootNode.leadingComments = (rootNode.leadingComments || []).concat(leadingComments); - if (trailingComments.length) rootNode.trailingComments = (rootNode.trailingComments || []).concat(trailingComments); + if (leadingComments.length && rootNode.leadingComments !== leadingComments) rootNode.leadingComments = (rootNode.leadingComments || []).concat(leadingComments); + if (trailingComments.length && rootNode.trailingComments !== trailingComments) rootNode.trailingComments = (rootNode.trailingComments || []).concat(trailingComments); } else { for (const targetNodeId of this.markedForDeletion) { try { diff --git a/tests/arborist.test.js b/tests/arborist.test.js index 75a40a9..17ba5a3 100644 --- a/tests/arborist.test.js +++ b/tests/arborist.test.js @@ -111,4 +111,25 @@ describe('Arborist tests', () => { arborist.applyChanges(); assert.equal(arborist.script, code, 'Invalid changes were applied.'); }); + it(`Verify comments aren't duplicated when replacing the root node`, () => { + const code = `//comment1\nconst a = 1, b = 2;`; + const expected = `//comment1\nconst a = 1;\nconst b = 2;`; + const arb = new Arborist(code); + const decls = []; + arb.ast.forEach(n => { + if (n.type === 'VariableDeclarator') { + decls.push({ + type: 'VariableDeclaration', + kind: 'const', + declarations: [n], + }); + } + }); + arb.markNode(arb.ast[0], { + ...arb.ast[0], + body: decls, + }); + arb.applyChanges(); + assert.equal(arb.script, expected); + }); }); \ No newline at end of file