esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Dynamic method names prevent tree shaking

Open quentinadam opened this issue 2 years ago • 0 comments

Using dynamic class method names prevents the class to be discarded by tree shaking when it is not used.

Example:

// input.js

const method = 'name';

class A {
  greet() {
    console.log('hello from A');
  }
  
  [method]() {
    return 'A';
  }
}

class B {
  greet() {
    console.log('hello from B');
  }
}

new B().greet();

I have tried to add various /* @__PURE__ */ annotations, but the class A does not get tree shaken. The above example is deliberately simple to demonstrate the issue, but the context where it came from is that any class that declares a custom inspect function like below prevents treeshaking:

[Symbol.for('nodejs.util.inspect.custom')]() {
  return '...';
}

Here is a link to the playground to reproduce the issue. https://esbuild.github.io/try/#dAAwLjE5LjExAC0tdHJlZS1zaGFraW5nPXRydWUAY29uc3QgbWV0aG9kID0gJ21ldGhvZCc7CgpjbGFzcyBBIHsKICBncmVldCgpIHsKICAgIGNvbnNvbGUubG9nKCdoZWxsbyBmcm9tIEEnKTsKICB9CiAgCiAgW21ldGhvZF0oKSB7CiAgICByZXR1cm4gJ0EnOwogIH0KfQoKY2xhc3MgQiB7CiAgZ3JlZXQoKSB7CiAgICBjb25zb2xlLmxvZygnaGVsbG8gZnJvbSBCJyk7CiAgfQp9CgpuZXcgQigpLmdyZWV0KCk7

quentinadam avatar Jan 14 '24 16:01 quentinadam