workerd icon indicating copy to clipboard operation
workerd copied to clipboard

Ensure CJS/MJS require interop in nodejs-compat

Open jasnell opened this issue 1 year ago • 0 comments

In Node.js, there is now experimental support for require('...') an ESM.

In Node.js, by default, requiring an ESM, the require returns the module namespace. There is a new PR, however, that will allow the ESM to indicate that the require should return the default export instead: https://github.com/nodejs/node/pull/54563

Example:

// a.mjs
export default class Foo {};
console.log(require('./a.mjs'));
// [Module: null prototype] { __esModule: true, default: [class Foo] }

With the PR

// a.mjs
export default class Foo {};
export const __cjsUnwrapDefault = true;
console.log(require('./a.mjs'));
// [class Foo]

When nodejs_compat_v2 mode is on, and we are calling require('...') from a CommonJS module, the new export should be honored.

jasnell avatar Aug 26 '24 02:08 jasnell