From 13d931c4176c1a80f86f3571968bbcde1c531cd2 Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Fri, 4 Aug 2017 16:00:29 -0700 Subject: [PATCH] Don't insert the same node into the AST multiple times (fixes babel/babili#556) (#6054) --- .../src/index.js | 6 +++++- .../test/copied-nodes.js | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 packages/babel-plugin-transform-es2015-modules-commonjs/test/copied-nodes.js diff --git a/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js b/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js index bc46255572..5861eaa847 100644 --- a/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js +++ b/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js @@ -73,7 +73,11 @@ export default function() { ), ); } else { - path.replaceWith(remap); + path.replaceWith( + // Clone the node before inserting it to ensure that different nodes in the AST are represented + // by different objects. + t.cloneWithoutLoc(remap), + ); } this.requeueInParent(path); }, diff --git a/packages/babel-plugin-transform-es2015-modules-commonjs/test/copied-nodes.js b/packages/babel-plugin-transform-es2015-modules-commonjs/test/copied-nodes.js new file mode 100644 index 0000000000..ee0c38fec5 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-modules-commonjs/test/copied-nodes.js @@ -0,0 +1,19 @@ +const assert = require("assert"); +const babel = require("babel-core"); + +test("Doesn't use the same object for two different nodes in the AST", function() { + const code = 'import Foo from "bar"; Foo; Foo;'; + + const ast = babel.transform(code, { + plugins: [[require("../"), { loose: true }]], + }).ast; + + assert.equal(ast.program.body[3].expression.type, "MemberExpression"); + assert.equal(ast.program.body[4].expression.type, "MemberExpression"); + + assert.notEqual( + ast.program.body[3].expression, + ast.program.body[4].expression, + "Expected different nodes in the AST to not be the same object", + ); +});