CJS output: an entry chunk for a CommonJS module gets extra exports that overwrite module.exports
Reproduction link or steps
// lib.js
module.exports = { value: 42 };// main.js
import lib from './lib.js';
console.log(lib.value);// rolldown.config.js
export default {
input: { main: './main.js', lib: './lib.js' },
output: { format: 'cjs' },
};Build, then run node dist/main.js.
What is expected?
dist/main.js logs 42, and require('./dist/lib.js') returns { value: 42 }.
What is actually happening?
The runtime is merged into the lib entry chunk, and its helpers are exported with module.exports =. dist/lib.js ends with:
module.exports = require_lib();
module.exports = __toESM;dist/main.js then reads the helper from that chunk:
const require_lib$1 = require("./lib.js");
// ...
require_lib$1.__toESM(require_lib$1)So main.js throws TypeError: require_lib$1.__toESM is not a function, and require('./dist/lib.js') returns the __toESM function instead of { value: 42 }.
The same happens with output.exports: 'default' and with preserveEntrySignatures: 'allow-extension'. If lib.js also requires an ESM module that main.js imports, that module is merged into lib.js as well, and the file ends with four module.exports = lines. preserveEntrySignatures: 'strict' avoids the bug, because the helpers then go to rolldown-runtime.js. ESM output runs, but lib.js gets extra exports there too.
System Info
rolldown main at b0820260b (1.2.11), checked with the integration fixture harness on Windows.Any additional comments?
The existing fixture crates/rolldown/tests/rolldown/topics/exports/entry_cjs_default_default shows this output. It has expectExecuted: false, and topics/exports/README.md lists it under "Bugs Found".
From reading the code: a CommonJS entry has no resolved exports, so exports-only becomes allow-extension for its chunk in code_splitting.rs, and runtime_merge_preserves_target_signature also treats it as export-less. At the same time, get_chunk_export_names always reports ["default"] for a CJS-wrapped entry. The chunk therefore gets the default export mode, and each extra export is rendered as another module.exports =.
Treating a CJS-wrapped entry as having a default export in those two checks fixes the default config (checked locally; it also changes the snapshots of entry_cjs_named_default and misc/cjs_entry_as_dependency, where the runtime moves to its own chunk). I can send a PR for that part. For allow-extension and false in CJS output, which direction would you prefer: report the extra exports so the chunk uses named exports (auto would then warn about mixed exports), or keep those merges out of CJS entry chunks?
Possibly related, but a different case: #10015.
Source: rolldown/rolldown