esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Feature request: deep analysed annotations for cjs -> esm

Open simon300000 opened this issue 3 years ago • 3 comments

Currently esbuild generate annotations for nodejs' cjs to esm lexer, which works well.

But if the input js file contains something like export * from 'package-x', The exports of package-x is not in the annotation.

will it be possible for esbuild to read the exports of package-x and "re-emit" in the annotation of output file?

simon300000 avatar Aug 20 '22 18:08 simon300000

FYI, nodejs uses cjs-module-lexer to lexically analyze source code to find exports. So we have several choices:

  1. Let esbuild annotate more names by analyzing other packages like you said. This would require esbuild to implement something like cjs-module-lexer. What's worse, it asks esbuild to read files that are not bundled (think of this scenario: a react-related library does not installed 'react' in its node_modules).
  2. Let cjs-module-lexer support parsing esbuild's code pattern of re-exports, they have already intentionally supported babel & typescript. So I just raised an issue there.

hyrious avatar Aug 20 '22 23:08 hyrious

It's probably possible to do this without modifying cjs-module-lexer (and also without reading the exports of the re-exported package). Modifying cjs-module-lexer to match esbuild's generated output based on identifiers would also not be robust because esbuild's generated identifiers can be renamed (to avoid collisions, or during minification). Instead, esbuild would have to emit something that matches what cjs-module-lexer is expecting. Maybe something like this (assuming that you are marking package-x as external):

0 && (module.exports = {
  ...require('package-x'),
  /* other exports */
});

This approach would also have the benefit of automatically working with older node versions which wouldn't ever get any fixes that might hypothetically be added to cjs-module-lexer.

evanw avatar Aug 22 '22 17:08 evanw

This seems to me a far better approach, will you make this extra annotation in esbuild?

simon300000 avatar Aug 23 '22 21:08 simon300000