Rich-Harris / butternut

The fast, future-friendly minifier
https://butternut.now.sh
MIT License
1.17k stars 17 forks source link

Bug: Object literals in unused variables #156

Open loilo opened 7 years ago

loilo commented 7 years ago

Raised by squashing ami.js

Unused local variables are discarded, their values are kept. That leads to issues if the respective value is an object literal which is invalid as a standalone statement.

I think UglifyJS provides a good solution by recursively walking the object literal and extracting all possible side effects, discarding the object afterwards.

I'm not sure why bare variable access is considered a side effect, but I assume there are good reasons for that?

Input:

function wrapper () {
  var any_var = {
    prop_1: any_value,
    prop_2: any_fn()
  }
}

Output Butternut 0.4.6:

function wrapper(){{prop_1:any_value,prop_2:any_fn()}}

Output UglifyJS 3.0.8:

function wrapper(){any_value,any_fn()}
loilo commented 7 years ago

Sometimes the object literal cannot be omitted, e.g. when a method is called on it. In this case it should be made sure that it will be put in parantheses.

Input:

function wrapper () {
  var any_variable = {}.toString()
}

Output Butternut 0.4.6:

function wrapper(){{}.toString()}

Output UglifyJS 3.0.8:

function wrapper(){({}).toString()}