diff --git a/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js b/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js index 3e4476b64..abecf1de3 100644 --- a/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js +++ b/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js @@ -2448,4 +2448,18 @@ describe("dce-plugin", () => { } ` ); + + thePlugin( + "should fix issue#611 - transforming fn decl to expr", + ` + function foo() { + function count() { + let count = 1; + bar(count); + return count; + } + return count; + } + ` + ); }); 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 9f3bdbfc2..796c08787 100644 --- a/packages/babel-plugin-minify-dead-code-elimination/src/index.js +++ b/packages/babel-plugin-minify-dead-code-elimination/src/index.js @@ -400,7 +400,8 @@ module.exports = ({ types: t, traverse }) => { const replaced = replace(binding.referencePaths[0], { binding, scope, - replacement + replacement, + replacementPath }); if (replaced) { @@ -936,7 +937,7 @@ module.exports = ({ types: t, traverse }) => { } function replace(path, options) { - const { replacement, scope, binding } = options; + const { replacement, replacementPath, scope, binding } = options; // Same name, different binding. if (scope.getBinding(path.node.name) !== binding) { @@ -976,6 +977,18 @@ module.exports = ({ types: t, traverse }) => { return; } + // https://github.com/babel/babili/issues/611 + // this is valid only for FunctionDeclaration where we convert + // function declaration to expression in the next step + if (replacementPath.isFunctionDeclaration()) { + const fnName = replacementPath.get("id").node.name; + for (let name in replacementPath.scope.bindings) { + if (name === fnName) { + return; + } + } + } + // https://github.com/babel/babili/issues/130 if (!t.isExpression(replacement)) { t.toExpression(replacement);