babel-plugin-minify-dead-code incorrect when var inside if
- Dominant language
- JavaScript
- Stars
- 4.4k
- Forks
- 217
- PR merge metrics
- No merged PRs in 30d
Description
**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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting): 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](https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&build=&builtIns=false&corejs=3.6&spec=false&loose=false&code_lz=GYVwdgxgLglg9mABMAFBBATGsEEpEDeAUIojMImptvGPsaaQG4CGATouwOYDOiAvIgDkAGkQAjIQG4SiAL6y2AUygg2SAAYsAJAW58AhILAgANqcQB-Tm16IAXMKFyNMuUA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=script&lineWrap=true&presets=env&prettier=false&targets=&version=7.16.12&externalPlugins=babel-plugin-minify-dead-code-elimination%400.5.1&assumptions=%7B%7D) (please uncheck "Bug fixes" after loading)
```js
function f(condition) {
if (condition) {
var args = ', b';
}
return `a${args != null ? args : ''}`;
}
```
**Actual Output**
```js
function f(condition) {
if (condition) {
var args = ', b';
}
return "a".concat(args);
}
```
**Expected Output**
```js
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:
```json5
{
mange: false,
evaluate: false,
removeUndefined: false
}
```
babelrc:
```json5
{
presets: [
['@babel/env', {modules: false}],
['minify', {mangle: false, evaluate: false, removeUndefined: false}]
]
}
```
**Additional context**
This arose when minifying (a PR for) the CoffeeScript compiler.
Contributor guide
Research direction
Reproduce the linked Babel REPL example through the Babel Node API with the supplied minify configuration. Trace babel-plugin-minify-dead-code's handling of the conditional var initializer, then add regression coverage for the shown input and verify that the generated output preserves the null check.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- babel, javascript
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100