babel-minify incorrectly removes code blocks guarded by `if`s with possible truthy conditions
- Dominant language
- JavaScript
- Stars
- 4.4k
- Forks
- 217
- PR merge metrics
- No merged PRs in 30d
Description
Original issue submitted by @mgol in https://github.com/babel/babel/issues/8237
## Bug Report
**Current Behavior**
A clear and concise description of the behavior.
`babel-minify` incorrectly removes code blocks guarded by `if`s with possible truthy conditions if the variable used to guard the block is declared inside of the `if` block.
**Input Code**
- REPL or Repo link if applicable:
REPL fails with `repl: traverse.clearCache is not a function` so I'm just attaching input code:
```js
passed = false;
if (false) {
var disableCloseEvents = true;
}
if ( !disableCloseEvents ) {
passed = true;
}
console.log(passed ? 'PASS' : 'FAIL');
```
**Expected behavior/code**
The code should be minified to something that logs `"PASS"` as the initial code has. Instead, it compiles to (prettyfied):
```js
passed=!1;
var disableCloseEvents;
!1, console.log(passed ? "PASS" : "FAIL");
```
**Babel Configuration (.babelrc, package.json, cli command)**
I just run `babel-minify my-test-file.js`, both with `babel-minify` `0.4.3` and `0.5.0-alpha.a24dd066`.
**Environment**
- Babel version(s): [e.g. v6.0.0, v7.0.0-beta.34] `7.0.0-beta.51` but v6 as well
- Node/npm version: [e.g. Node 8/npm 5] Node v8.11.3, Yarn 1.7.0
- OS: [e.g. OSX 10.13.4, Windows 10] macOS 10.13.5 (17F77)
- Monorepo [e.g. yes/no/Lerna] no
- How you are using Babel: [e.g. `cli`, `register`, `loader`] via `babel-minify` from the command line and via [babel-minify-webpack-plugin](https://www.npmjs.com/package/babel-minify-webpack-plugin).
When used with `babel-minify-webpack-plugin` the code starts working correctly only if I set both `deadcode` & `simplify` to `false` (see https://github.com/babel/minify/tree/master/packages/babel-preset-minify#options for more details about the config).
**Possible Solution**
**Additional context/Screenshots**
This issue makes Babel Minify break AngularJS Material `1.1.9` & `1.1.10` (it worked fine with `1.1.8`). This piece of code:
https://github.com/angular/material/blob/v1.1.10/src/components/sidenav/sidenav.js#L363-L366
is stripped out incorrectly. This seems to be because Babel incorrectly treats the following code:
https://github.com/angular/material/blob/v1.1.10/src/components/sidenav/sidenav.js#L309-L311
If you move the variable declaration to the outside of the `if` in my test case, it starts working:
```js
passed = false;
var disableCloseEvents;
if (false) {
disableCloseEvents = true;
}
if ( !disableCloseEvents ) {
passed = true;
}
console.log(passed ? 'PASS' : 'FAIL');
```
Contributor guide
Assessment
This issue has not been assessed yet.