rollup icon indicating copy to clipboard operation
rollup copied to clipboard

Treeshake constants in if statements

Open manucorporat opened this issue 6 years ago • 2 comments

  • Rollup Version: 1.14.5
  • Operating System (or Browser): osx and browser
  • Node Version: 12.0.0

How Do We Reproduce?

https://rollupjs.org/repl?version=1.14.5&shareable=JTdCJTIybW9kdWxlcyUyMiUzQSU1QiU3QiUyMm5hbWUlMjIlM0ElMjJtYWluLmpzJTIyJTJDJTIyY29kZSUyMiUzQSUyMmNvbnN0JTIwQlVJTEQlMjAlM0QlMjB0cnVlJTNCJTVDbiU1Q25mdW5jdGlvbiUyMGhvbGEoZmxhZ3MpJTIwJTdCJTVDbiU1Q3RpZiUyMChmbGFncyUyMCU3QyU3QyUyMEJVSUxEKSUyMCU3QiU1Q24lNUN0JTVDdGNvbnNvbGUubG9nKCdoZWxsbycpJTNCJTVDbiU1Q3QlN0QlNUNuJTdEJTVDbiU1Q25jb25zb2xlLmxvZyhob2xhKSU1Q24lMjIlMkMlMjJpc0VudHJ5JTIyJTNBdHJ1ZSU3RCU1RCUyQyUyMm9wdGlvbnMlMjIlM0ElN0IlMjJmb3JtYXQlMjIlM0ElMjJjanMlMjIlMkMlMjJuYW1lJTIyJTNBJTIybXlCdW5kbGUlMjIlMkMlMjJhbWQlMjIlM0ElN0IlMjJpZCUyMiUzQSUyMiUyMiU3RCUyQyUyMmdsb2JhbHMlMjIlM0ElN0IlN0QlN0QlMkMlMjJleGFtcGxlJTIyJTNBbnVsbCU3RA==

Notice that:

if (CONSTANT || variable) { }

is property treeshaken, but:

if (variable || CONSTANT) { }

is not.

I am aware of the lazy evaluation of the binary operators, but if the "variable" is a pure expression and the CONSTANT is actually constant, this transform should be safe.

Expected Behavior

It should generate:

function hola(flags) {
	{
		console.log('hello');
	}
}

console.log(hola);

Actual Behavior

'use strict';

const BUILD = true;

function hola(flags) {
	if (flags || BUILD) {
		console.log('hello');
	}
}

console.log(hola);

manucorporat avatar Jun 09 '19 17:06 manucorporat

The reason is that if-statement tree-shaking uses a very generic method built into all nodes getLiteralValueAtPath. This function returns a primitve value or UNKNOWN_VALUE if it cannot be determined, which is the case here.

One way to improve this, and at the same time improve tree-shaking for conditional and logical expressions as well, could be to introduce additional values, e.g. UNKNOWN_TRUTHY_VALUE and UNKNOWN_FALSY_VALUE. Then code relying on the exact value could still check if it is unknown (there are several ways. For instance all unknown properties could be instances of Symbol, or all unknown properties could be objects, etc.) while code relying on truthiness could work with the new values as well. Also, functions and objects could return UNKNOWN_TRUTHY_VALUE.

lukastaegert avatar Jun 10 '19 05:06 lukastaegert

This has been fixed in v4.29.0 by https://github.com/rollup/rollup/pull/5763

cyyynthia avatar Aug 01 '25 18:08 cyyynthia