Skip to content

CJS named export "default" is not recognized as the default export entry #48899

@legendecas

Description

@legendecas

Version

v20.5.0

Platform

Darwin my.local 21.6.0 Darwin Kernel Version 21.6.0: Sat Jun 18 17:07:22 PDT 2022; root:xnu-8020.140.41~1/RELEASE_ARM64_T6000 arm64

Subsystem

module

What steps will reproduce the bug?

With two scripts, namely "my-mod.mjs" and "my-cjs.cjs", and their contents as:

// my-mod.mjs

import foo from './my-cjs.cjs'
console.log(foo);
// my-cjs.cjs
exports.default = "foo";

Run with node my-mod.mjs.

How often does it reproduce? Is there a required condition?

Always

What is the expected behavior? Why is that the expected behavior?

Output foo.

What do you see instead?

Output { default: 'foo' }

Additional information

The original problem here is that I found a typescript module written as:

const foo = 'foo';
export {
    foo as default
};

is compiled as the following when targeting CJS: (playground)

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = void 0;
const foo = 'foo';
exports.default = foo;

If the module is imported from an ESM module in Node.js, the default export entry would not be the expected one written originally in typescript.

The spec https://tc39.es/ecma262/#sec-static-semantics-importentriesformodule states that ImportedDefaultBinding imports the "default" entry from the requested module.

When using with vm.SyntheticModule, the following script outputs the expected result:

import vm from 'vm';

const context = vm.createContext();
context.print = console.log;

const mod = new vm.SourceTextModule(`
import foo from 'foo';
console.log(foo);
`);
await mod.link(async () => {
  const mod = new vm.SyntheticModule(['default'], () => {
    mod.setExport('default', 'foo');
  });

  return mod;
});
await mod.evaluate(); // outputs "foo"

Metadata

Metadata

Assignees

No one assigned

    Labels

    moduleIssues and PRs related to the module subsystem.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions