babel / babel/minify

Sometimes scopes are unsafely removed, breaking code

Open
#935 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
4.4k
Forks
217
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**

babel-minify sometimes eliminates a scope (i.e. pairs of braces, e.g. `{ ... }`) when it is unsafe to do so, resulting in broken code.

**To Reproduce**

```js
{
const foo = 1;
}
```

**Actual Output**

```js
const a=1;
```

Note the enclosing scope was removed. This defeats the purpose of using the scope to prevent namespace pollution in the outer scope.

**Expected Output**

```js
{
const a=1;
}
```

Note the enclosing scope is preserved. This avoids the `const` declaration using its name in the outer scope.

Another way to demonstrate how this is an incorrect optimisation is the following code:

```js
{
const foo = 1;
}

{
const bar = 2;
}
```

This fails to minify, because babel-minify renames both `const` declarations to `a`, removes both enclosing scopes, and then crashes with `Duplicate declaration "a"`.

**Configuration**

Demo URL:

https://babeljs.io/en/repl#?babili=true&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=N4KABBYMYPYHYGcAuYBmMZgLxgIwG4QBfEEUSaeZMAIwEMAnbMAJkKKA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=false&presets=babili&prettier=false&targets=&version=6.26.0&envVersion=

**Possible solution**

It looks like the only safe option is to entirely avoid variable declarations in scopes. This is very difficult if you are using classic mode scripts and use a file-level scope to avoid polluting the global namespace.

Contributor guide

Open the contributing guide

Research direction

Start by running the two JavaScript examples through babel-minify and comparing the actual and expected output. Done means preserving scopes around the const declarations and avoiding the reported Duplicate declaration "a" crash when two such scopes are minified.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.