esbuild-plugin-commonjs icon indicating copy to clipboard operation
esbuild-plugin-commonjs copied to clipboard

feat: transform commonjs to esm

Open hyrious opened this issue 3 years ago • 9 comments

I came up with a super easy way of doing this instead of going "syntheticNamedExports". To be clear I just want to replicate the node17 behavior: use cjs-module-lexer to support partial of the cjs modules. The transformed module will be like:

var exports = {}, module = {exports}
// have to use { block } to prevent names conflict
{
  // original code
}
export default module.exports
// analyzed possible named exports
export var useState = module.exports.useState
...

The downside is obvious: some modules will cause error at runtime when it doesn't follow the pattern. But the advantage is we can reduce some verbosing code about __commonJS. I can make this transformation optional.

Those requires still need the trick in this repo. But I want to add additional info here:

try { require("x") } catch {}

Code like this won't be transformed to import statement because esbuild allowed this pattern and it won't warn about it. Frankly speaking, even "require is undefined" won't cause error at runtime when it was caught like this.

hyrious avatar Feb 21 '22 13:02 hyrious

Preview Link if the proposal of this issue come true.

hyrious avatar Feb 21 '22 13:02 hyrious

🚢 0.2.0 I'll keep this issue open if there be any improvements to the conversion or strong reasons to remove this feature.

hyrious avatar Feb 22 '22 03:02 hyrious