Skip to content

Dynamic imports not transformed to require calls when format is cjs #6511

@TimoGlastra

Description

@TimoGlastra

Reproduction link or steps

Reproduction: https://github.com/TimoGlastra/tsdown-dynamic-import. Instructions on how to run in readme.

What is expected?

Source code is written as:

export async function run() {
  const myLib = await import("some-lib");
}

run();

With tsdown format set the cjs. I would expect the dynamic import to be rewritten as a dynamic require:

//#region src/index.ts
async function run() {
  require("some-lib");
}
run();

//#endregion
exports.run = run;

What is actually happening?

The dynamic import is kept when format is CJS:

//#region src/index.ts
async function run() {
  await import("some-lib");
}
run();

//#endregion
exports.run = run;

Any additional comments?

I was able to work around it with a hacky plugin. But this doesn't feel like a good solution.

We are importing this in React Native, and with the TSC compiler we used require. Now that we are migrating to ESM we are updating all dynamic requires to dynamic imports. But we would like the CJS output to match the previous behvaiour to make the migration to ESM as smooth as possible.

Metadata

Metadata

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions