esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Boolean tree-shaking

Open intrnl opened this issue 3 years ago • 1 comments

There's a pattern that's being used over in Preact that would allow class components to be tree-shaken easily, including the relevant rendering code, which works more or less like this.

esbuild REPL Rollup REPL

let ENABLE_COMPONENT = false;

export class Component {
  constructor () {
    ENABLE_COMPONENT = true;
  }
  
  render () {}
}

export function h (type, props, ...children) {
  if (children.length > 0) {
    props = { ...props, children };
  }
  
  return { type, props };
}

export function render (node) {
  const type = node.type;

  if (ENABLE_COMPONENT && type.prototype instanceof Component) {
    const instance = new type();
    node._instance = instance;
  }
  
  return node;
}

It would be nice if esbuild could tree-shake this properly.

intrnl avatar Aug 02 '22 04:08 intrnl

Multi-level optimizations like this are currently out of scope, sorry. The optimizer would have to deduce that Component isn't used (since it's only used for instanceof), which would then need to cause ENABLE_COMPONENT to be re-analyzed as a constant, which would then need to inline the constant false everywhere, which would need to re-do tree shaking, which could cause other optimizations, etc. This is a worklist algorithm that needs to iterate multiple times (typically until a fixed point is reached).

It's a cool optimization but esbuild isn't built to optimize this way. Everything about esbuild's current internals is designed for speed, and esbuild basically only does a single optimization pass. So addressing this would involve invalidating the fundamental assumption of how esbuild works and reworking everything that falls out from that. In addition, the AST would likely also need to be redone to be able to track precise read/write reference counts for symbols to handle invalidations due to incremental updates. Right now symbol reference counts are only approximate.

evanw avatar Aug 02 '22 11:08 evanw