Closed viktomas closed 3 months ago
Similar issue raised before: https://github.com/evanw/esbuild/issues/2056
esbuild transforms all top-level const
to var
to avoid a TDZ performance issue. This is a trade-off to have better performance rather than keeping native behavior.
Rollup does report circular dependency warnings, however that does not always mean a runtime error. If you write your code in a way that all side-effects (mainly initialization statements) are happen in a constructor / init function and make sure they are called after all dependencies being loaded, this issue disappear even if there is circular dependencies.
I'm already aware of esbuild's behavior regarding this case. There is a FAQ entry on why esbuild does things this way: https://esbuild.github.io/faq/#top-level-var
Ok, got you, thanks @hyrious and @evanw for your response 🙏 It makes sense; I'll close this issue.
To anyone who's reading this thread. I strongly recommend using the eslint-plugin-import/docs/rules/no-cycle eslint rule as a prevention of some of the issues that can be caused by the top-level-var
design choice 👍
I'm not sure if this issue can be fixed by
esbuild
. I want to raise it for awareness, if not anything else. Also, a huge thank you, Evan, for building and maintaining this project 🙇A plain
node
with ES modules seems to be able to detect this issue at module loading time whilstesbuild
produces a bundle.The issue
The issue is, that circular dependency is not detected at bundling time. This leads to a bug in the bundled code that's hard to understand.
compiling this code with
produces this code
which when run produces this output
Again, I'm not sure that this can be solved by
esbuild
without implementing some more complex static analysis like whateslint-plugin-import/no-cycle
rule does.Comparison with plain node
I tried this same scenario in node 21.7. I tried both CommojJS and ES modules, and both produced useful errors or warnings.
I read this response https://github.com/evanw/esbuild/issues/1582#issuecomment-915401785 on an existing closed issue that was making distinction between runtime and "compile-time" error (as in module loading time). I think that at least for ES modules, this is a compile time error.
ES modules
running
node index.js
produces what is IMO a compile-time error (sidenote: you have to specify type: module inpackage.json
)CommonJS
running
node index.js
runs the code but produces a warning