diff --git a/packages/babel-plugin-minify-dead-code-elimination/__tests__/fixtures/issue-685/actual.js b/packages/babel-plugin-minify-dead-code-elimination/__tests__/fixtures/issue-685/actual.js new file mode 100644 index 000000000..c39141aea --- /dev/null +++ b/packages/babel-plugin-minify-dead-code-elimination/__tests__/fixtures/issue-685/actual.js @@ -0,0 +1,16 @@ +function loop() { + var end = 0; + var start = end; + while (end < 10) { + console.log(start, end); + var end = end + 1; + } +} +loop(); + +function bar() { + var x = 1; + var y = x + 2; + var x = 3; + return x + y; +} diff --git a/packages/babel-plugin-minify-dead-code-elimination/__tests__/fixtures/issue-685/expected.js b/packages/babel-plugin-minify-dead-code-elimination/__tests__/fixtures/issue-685/expected.js new file mode 100644 index 000000000..62b3623b5 --- /dev/null +++ b/packages/babel-plugin-minify-dead-code-elimination/__tests__/fixtures/issue-685/expected.js @@ -0,0 +1,16 @@ +function loop() { + var end = 0; + var start = end; + while (end < 10) { + console.log(start, end); + var end = end + 1; + } +} +loop(); + +function bar() { + var x = 1; + var y = x + 2; + var x = 3; + return x + y; +} \ No newline at end of file diff --git a/packages/babel-plugin-minify-dead-code-elimination/src/index.js b/packages/babel-plugin-minify-dead-code-elimination/src/index.js index 037fccefa..448fa7d18 100644 --- a/packages/babel-plugin-minify-dead-code-elimination/src/index.js +++ b/packages/babel-plugin-minify-dead-code-elimination/src/index.js @@ -349,9 +349,16 @@ module.exports = ({ types: t, traverse }) => { let bail = false; if (replacementPath.isIdentifier()) { - bail = - refPath.scope.getBinding(replacement.name) !== - scope.getBinding(replacement.name); + const binding = scope.getBinding(replacement.name); + // the reference should be in the same scope + // and the replacement should be a constant - this is to + // ensure that the duplication of replacement is not affected + // https://github.com/babel/minify/issues/685 + bail = !( + binding && + refPath.scope.getBinding(replacement.name) === binding && + binding.constantViolations.length === 0 + ); } else { replacementPath.traverse({ Function(path) { @@ -362,9 +369,13 @@ module.exports = ({ types: t, traverse }) => { if (bail) { return; } - bail = - refPath.scope.getBinding(node.name) !== - scope.getBinding(node.name); + const binding = scope.getBinding(node.name); + if ( + binding && + refPath.scope.getBinding(node.name) === binding + ) { + bail = binding.constantViolations.length > 0; + } } }); }