Skip to content

Export commonjs named exports in ESM #442

@remorses

Description

@remorses

Currently a module that uses commonjs features like exports and require will translate to a default export exporting the module.exports object.

But some packages like react rely on bundlers like webpack to allow you to use named imports like import { useEffect } from 'react', event thought react is a commonjs module.

It would be cool to detect the cjs named exports and reexport them in the ESM output.

Code

currently executing esbuild --bundle --outdir=out --format=esm x.json

exports.x = 9

becomes

...
var require_x = __commonJS((exports, module) => {
  module.exports.x = 9;
});
export default require_x();

what i am asking for is to have this output

...
var require_x = __commonJS((exports, module) => {
  module.exports.x = 9;
});
export default require_x();

export {
  x: require_x().x
}

Nodejs is trying to allow the same interopability and they are using a lexer to detect commonjs named exports: https://github.com/guybedford/cjs-module-lexer

That package implements the lexer in C and uses WASM to execute it in js, we could use the same code nodejs uses to detect commonjs named exports and reexport them as ESM

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions