Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Treeshaking appears to only work at the top-level #2967

Closed
thebanjomatic opened this issue Mar 4, 2023 · 2 comments
Closed

Treeshaking appears to only work at the top-level #2967

thebanjomatic opened this issue Mar 4, 2023 · 2 comments

Comments

@thebanjomatic
Copy link

When variables are un-used at the top-level of a module, tree-shaking kicks in unused code is properly dropped from the output. For example, the code below correctly results in empty output (with --tree-shaking) because foo is not referenced. If you uncomment the console.log(foo) at the bottom, or add export {foo} etc, then all of the associated code persists.

function getFoo() {
  window.alert('getting foo...');
  return 5;
}
const foo = /*#__PURE__*/ getFoo();
// console.log(foo)

All of the above works great, but if you take the exact same code and wrap it in a function, no code is eliminated from the body of the function.

(function () {
  function getFoo() {
    window.alert('getting foo...');
    return 5;
  }
  const foo = /*#__PURE__*/ getFoo();
})();

Would it be difficult to apply the same analysis to function bodies that applies at the top-level and drop any side-effect-free expressions that are not visible to a return value?

@evanw
Copy link
Owner

evanw commented Mar 4, 2023

Would it be difficult to apply the same analysis to function bodies that applies at the top-level and drop any side-effect-free expressions that are not visible to a return value?

Yes. The data structure that esbuild uses for tree-shaking makes a graph of top-level statements and is not recursive. It's designed to run quickly and give good results when bundling from source (since esbuild is primarily a bundler), but that means it's not designed to be optimal for all use cases. There is more discussion in this issue (which is the same request as yours): #639.

@thebanjomatic thebanjomatic closed this as not planned Won't fix, can't repro, duplicate, stale Mar 4, 2023
@thebanjomatic
Copy link
Author

Closing in favor of #639

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants