babel / minify

:scissors: An ES6+ aware minifier based on the Babel toolchain (beta)
https://babeljs.io/repl
MIT License
4.39k stars 225 forks source link

babel-plugin-minify-dead-code incorrect when var inside if #1021

Open edemaine opened 2 years ago

edemaine commented 2 years ago

Describe the bug

TLDR: babel-plugin-minify-dead-code seems to assume that var initializers are executed, but they're executed only if reached.

Longer version: var x = y does two things: it declares x at the function scope (no matter what), and sets x = y when that line gets reached. As a result, if (condition) var x = y declares x, but x will remain undefined if condition is false. babel-plugin-minify-dead-code seems to assume that the assignment happens though, and generates incorrect code.

To Reproduce

Demo link (please uncheck "Bug fixes" after loading)

function f(condition) {
  if (condition) {
    var args = ', b';
  }
  return `a${args != null ? args : ''}`;
}

Actual Output

function f(condition) {
  if (condition) {
    var args = ', b';
  }

  return "a".concat(args);
}

Expected Output

function f(condition) {
  if (condition) {
    var args = ', b';
  }

  return "a".concat(args != null ? args : '');
}

Configuration

How are you using babel-minify?

babel Node API

babel-minify version: 0.5.1

babel version : 7.15.5

babel-minify-config:

{
  mange: false,
  evaluate: false,
  removeUndefined: false
}

babelrc:

{
  presets: [
   ['@babel/env', {modules: false}],
   ['minify', {mangle: false, evaluate: false, removeUndefined: false}]
  ]
}

Additional context

This arose when minifying (a PR for) the CoffeeScript compiler.