top | item 28026190

(no title)

thosakwe | 4 years ago

I wonder why tree-shaking wasn't always the default for, say, JS bundlers. If a compiler/analyzer knows what the entry point of a program is, as well as any symbols it exports to the outside world, isn't it relatively simple to figure out what's not being used?

I could be misunderstanding something.

discuss

order

Forge36|4 years ago

Couple of weird language edge cases

JS allows functions to by called by name.

A.foo();

Can be

A["foo"]()

Because foo is now a string it's possible to add levels of indirection.

Action(name) { A[name](); }

It's possible the list of actions to perform are sent to the client as data.

This amiguity has left enough doubt for most tools, and people making tree shaking a practice on code not commonly performed. The longer that happens the scarier it becomes to start investigating.

Since the browser will tree shake for you the incentive to cleanup your source is also less important.

chadlavi|4 years ago

But in this case A is exported. No one is going to tree shake methods of a class.

wyager|4 years ago

Dead code elimination is only straightforward if your language has sane naming semantics (lexical scope, static name resolution, etc). If your language does crazy stuff like allowing function lookup by the string representation of its name in the source code (e.g. JavaScript) it becomes much harder.

wffurr|4 years ago

Which is why Google's jscompiler requires a stricter subset of JS for "advanced optimizations" including dead code elimination.

_3u10|4 years ago

C allows you to call functions by string...

C++ also allows it, but the function names are a bit harder to guess.

giorgioz|4 years ago

I think tree-shaking will be a default in new JS bundler. ESbuild seem to enable it by default: https://esbuild.github.io/

I think the reason some other bundlers like webpack didn't/don't have it by default is because tree-shaking became popular after they were invented and tree-shaking was added to the bundler later on as an extra nice-to-have feature.

It seems webpack has built-in support for tree-shaking from version 2. Latest version of webpack might have it enabled by default (not 100% sure but possible) https://webpack.js.org/guides/tree-shaking/