esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Global 'use strict' for bundling in CJS is erroneous

Open tinovyatkin opened this issue 3 years ago • 1 comments

Respecting alwaysStrict introduced in #2264 is OK for compiling your own modules but it's definitely a breaking problem for bundling in CJS mode - 'use strict' is per-file directive and strict mode file can perfectly require some sloppy mode file and everything will continue working.

While in bundling targeting CJS with global 'use strict' those internal dependencies made for sloppy mode (unfortunately still very broad case) will just break in some hard to debug way. So, I believe alwaysStrict should not be applied to bundling in CJS or applied only when every dependency is also in global strict mode already.

tinovyatkin avatar Jul 10 '22 16:07 tinovyatkin

There is unfortunately no way to turn strict mode off in JavaScript (by design), which I think means it's impossible for esbuild to honor use strict accurately when bundling. This is because esbuild does "scope flattening" which puts ESM files in the top-level scope. You're going to get either false positives (nested CJS files are incorrectly in strict mode) or false negatives (top-level ESM files are incorrectly in sloppy mode) and it's up to you which one you pick. If you want the output to be use strict then you can tell esbuild to emit use strict, and if you don't want the output to be use strict then you can tell esbuild to not emit use strict.

A hypothetical alternative could be for esbuild to convert all ESM files into CJS during bundling, but that would disable tree shaking and would bloat the bundle with lots of wrappers, which I'm guessing very few people would actually want. It would also make esbuild's linker even more complex which is not something I want to do without a good reason. So I don't think this alternative is worth doing.

evanw avatar Jul 10 '22 17:07 evanw

I'm closing this issue as "won't fix" for the reason described above.

evanw avatar Dec 04 '22 04:12 evanw