Unused import bundled unless define test is on same line for class methods only
- Dominant language
- Go
- Stars
- 40.1k
- Forks
- 1.3k
- PR merge metrics
- No merged PRs in 30d
Description
When given a define, esbuild is able to treeshake some known dead code. This does not work for class methods unless the define is tested on the same line.
```
esbuild --bundle --format=esm --minify --tree-shaking --define:debug=false entry.ts
```
```ts
import {a, b} from './file.ts'
class C {
init(): void {
if (!debug) return
if (debug) a()
b()
}
}
new C()
```
```ts
export function a(): void {
console.log('a')
}
export function b(): void {
console.log('b')
}
```
Produces `function i(){console.log("b")}var o=class{init(){}};new o;` when no logs were expected `var o=class{init(){}};new o;`.
It seems to be method specific. [This code shakes fine](https://esbuild.github.io/try/#YgAwLjI1LjAALS1idW5kbGUgLS1mb3JtYXQ9ZXNtIC0tbWluaWZ5IC0tdHJlZS1zaGFraW5nIC0tZGVmaW5lOmRlYnVnPWZhbHNlAGUAZW50cnkudHMAaW1wb3J0IHthLCBifSBmcm9tICcuL2ZpbGUudHMnCgpmdW5jdGlvbiAgaW5pdCgpOiB2b2lkIHsKICBpZiAoIWRlYnVnKSByZXR1cm4KICBpZiAoZGVidWcpIGEoKQogIGIoKQp9Cgppbml0KCkAAGZpbGUudHMAZXhwb3J0IGZ1bmN0aW9uIGEoKTogdm9pZCB7CiAgY29uc29sZS5sb2coJ2EnKQp9CgpleHBvcnQgZnVuY3Rpb24gYigpOiB2b2lkIHsKICBjb25zb2xlLmxvZygnYicpCn0):
```ts
import {a, b} from './file.ts'
function init(): void {
if (!debug) return
if (debug) a()
b()
}
init()
```
[Playground](https://esbuild.github.io/try/#YgAwLjI1LjAALS1idW5kbGUgLS1mb3JtYXQ9ZXNtIC0tbWluaWZ5IC0tdHJlZS1zaGFraW5nIC0tZGVmaW5lOmRlYnVnPWZhbHNlAGUAZW50cnkudHMAaW1wb3J0IHthLCBifSBmcm9tICcuL2ZpbGUudHMnCgpjbGFzcyBDIHsKICBpbml0KCk6IHZvaWQgewogICAgaWYgKCFkZWJ1ZykgcmV0dXJuCiAgICBpZiAoZGVidWcpIGEoKQogICAgYigpCiAgfQp9CgpuZXcgQygpAABmaWxlLnRzAGV4cG9ydCBmdW5jdGlvbiBhKCk6IHZvaWQgewogIGNvbnNvbGUubG9nKCdhJykKfQoKZXhwb3J0IGZ1bmN0aW9uIGIoKTogdm9pZCB7CiAgY29uc29sZS5sb2coJ2InKQp9)
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by running the provided esbuild command with entry.ts and file.ts, then compare the class-method case with the standalone init function in the examples. The fix is done when the class-method case tree-shakes the unused imports and produces the expected output without the unused function.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- build-system, compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100