Skip to content

CJS output: (await import("./x")).default is the exports object instead of the default export #577

Open

Description

@trackoor

Environment

  • unbuild: 3.6.1 (rollup 4.68.0) and main (cf1c303)
  • Node.js: v26.13.0

Reproduction

src/index.ts:

export async function getPlugin() {
  const mod = await import("./plugin");
  return mod.default;
}

src/plugin.ts:

export default function plugin() { return "plugin ran"; }
export const version = 1;

build.config.mjs:

export default { entries: ["src/index"], rollup: { emitCJS: true }, declaration: false };

package.json:

{"name":"demo","version":"1.0.0","type":"module"}

Commands:

npx unbuild
node -e 'require("./dist/index.cjs").getPlugin().then(p => console.log("cjs:", typeof p))'
node -e 'import("./dist/index.mjs").then(m => m.getPlugin()).then(p => console.log("esm:", typeof p))'

Actual output:

cjs: object
esm: function

Expected output:

cjs: function
esm: function

Describe the bug

With rollup.emitCJS: true, a dynamic import of a local module is preserved as import('./chunks/plugin.cjs') in dist/index.cjs, while dist/chunks/plugin.cjs sets exports.default = plugin. Because Node.js exposes module.exports as default when import() loads a CommonJS file (https://nodejs.org/api/esm.html#commonjs-namespaces), mod.default resolves to { default: [Function: plugin] } instead of the function itself.

Additional context

This happens because the preserveDynamicImports plugin (enabled by default) also rewrites dynamic imports of internal chunks; without it, Rollup emits Promise.resolve().then(() => require('./chunks/plugin.cjs')), where .default is the function.

Credit: https://ucsbplse.github.io/

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions