Repository navigation
Conversation
A JSON, JSONC, JSON5, TOML, YAML or XML file that something loads with
require() or a non-split import() gets the CommonJS form. Each ES import
of it goes through __toESM, which applies the __esModule interop of
CommonJS modules to the data: a default import of
{ "__esModule": true, "default": 5 } was 5.
Such a file is a value, not a CommonJS module. The linker marks each ES
import record of it, and the printer passes isNodeMode, so default is the
whole value whatever the importer is.
|
Updated 9:08 AM PT - Oct 24th, 2026
✅ @robobun, your commit 4b74b07e9a1fdff27f5453ecaeef560cc24d9e14 passed in 🧪 To try this PR locally: bunx bun-pr 46736That installs a local version of the PR into your bun-46736 --bun |
|
Status: ready for review. CI passed on the head commit 4b74b07 (build 132014, 181 of 181 jobs). Reproduced on main (5c6d4e2) and on the 1.4.1 and 1.4.2 releases: // data.json: { "__esModule": true, "default": 5, "x": 1 }
// entry.js
import json from "./data.json";
console.log(JSON.stringify(json), json === require("./data.json"));
The 33 new cases in |
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Classify data files and assign import flags src/ast/import_record.rs, src/bundler/LinkerContext.rs, src/bundler/linker_context/scanImportsAndExports.rs, src/bundler/linker_context/README.md |
The linker identifies CommonJS-exported JSON, JSONC, JSON5, TOML, YAML, and XML files. It assigns TO_ESM_NODE_MODE to applicable imports, except imports converted from require(). |
Use import flags when printing interop src/js_printer/lib.rs |
The printer checks the import record when deciding whether to emit the Node-mode argument to __toESM. Internal import and require paths now pass the import record to the suffix printer. |
Validate data-file import behavior test/bundler/bundler_loader.test.ts |
Tests cover default values and identity across imports, requires, re-exports, chunks, output formats, and dynamic imports for data-file fixtures. |
Suggested reviewers: jarred-sumner, dylan-conway, alii
Priority:
Merge Risk: 
Minimal · up to e3adc
-
No actionable merge-blocking issue was established; the change is ready for normal checks.
Pre-merge checks: 
4
-
Full details: Description check
-
Explanation
The description states the problem, the fix, verification, and downsides, and gives reproduction steps, measurements, and tests. It fills the template's two sections, "What does this PR do?" (as Problem/Fix/Background) and "How did you verify your code works?" (as Verified/Tests). The description is thorough and specific, and it matches the code changes in the raw summary, which cover the new TO_ESM_NODE_MODE flag, is_commonjs_data_file, to_esm_flags, print_to_esm_suffix, and the new tests.
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Beyond the inline findings, I also checked the print_to_esm_suffix signature change — all four printer call sites (including the .then((m)=>__toESM(m.default path) still emit ,1 for an ESM-typed importer because the old input_module_type == Esm condition is OR'd into to_esm_is_node_mode, and the exports_kind reads in to_esm_flags during step 6 come after the only writes to that column (step 1, scanImportsAndExports.rs:207-383), so there is no torn read.
Extended reasoning...
The change adds a TO_ESM_NODE_MODE import-record flag set by the linker for ES imports of CommonJS-form data files and consumed by the printer to emit __toESM(x, 1); it touches the bundler linker and JS printer only, with no security-sensitive surface. Four inline findings remain (two intentional behavioral divergences from bun run that need a maintainer call, an untested Xml loader arm, and the unchanged external-CJS sibling site), so a human review is needed.
…ata file rule A file of a lifted CommonJS package that is module.exports = require(x) prints that statement through the record of an export star. With isNodeMode, require() of that file gave the whole data as .default, where Node gives the default key of the data. A statement of a lifted CommonJS file was a require(), so it keeps the namespace it has. What an onLoad plugin returns is not changed: a result with loader: "object" is the exports of a module and reaches the linker as JSON. An XML value has one key, so it cannot have both __esModule and default. The xml loader is not in the rule.
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-24. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Problem
import json from "./data.json"is5for{ "__esModule": true, "default": 5 }when another file loads it withrequire()orimport().bun runand Node give the whole object.__toESM(src/runtime.js:58) applies the CommonJS__esModulerule to the data.Fix
to_esm_flags(src/bundler/LinkerContext.rs) marks each ES import record of such a file withTO_ESM_NODE_MODE. The printer prints__toESM(require_data(), 1), sodefaultis the whole value.json,jsonc,json5,toml,yaml. Other loaders print the same bytes.test/bundler/bundler_loader.test.ts(33 new cases, all fail on main) and all oftest/bundler/.Background
__toESM(mod, isNodeMode)builds the namespace object of a CommonJS module. WithoutisNodeMode, a truthymod.__esModulemakesdefaultbemod.default.isNodeModecame from the importer: the output format, then its syntax (1.3.1), then its module type (1.4.1, bundler: pick the __toESM interop from the importer's module type #41150). Each rule left some importers at5.require_data(), without__toESM: a separate output-size change.Downsides
5. No issue reports it.bun run(5): an import of a file that is onlymodule.exports = require("./data.json")(Notes).WeakMaps, not 1. Releasetext: +1,536 bytes.Notes
Repro
bun entry.jsprints the whole object. Node v26.3.0 prints the whole object for the import,require()andimport()(withwith { type: "json" }). webpack 5.112 prints the whole object. esbuild 0.21.5 and 0.28.2 print5. rolldown 1.2.15 prints5for therequire()shape.No issue reports this. It was found by a read of the code after #41150. The trigger is a data file with a truthy
__esModulekey and adefaultkey, which is rare.History, by importer shape
Value of the default import of that
data.json, from the released binaries. "whole" is the whole object..jsimporter with ES syntax only, plus arequire()--format=cjsimportandmodule.exportsimport()from a.cjsimportermodule.exports = require("./data.json"), ES module output.mjsimporterRows 1, 2 and 5 gave the whole object in 1.4.0 and give
5from 1.4.1 (#41150). Rows 3 and 4 have given5since 1.3.1 (#23803). With this PR the value does not depend on the importer.What the rule covers
import * as,export ... from,export *, a non-splitimport(), and animport()of the file's own chunk. The loader is the one the file was parsed with, sowith { type: "json" }and--loader .x:jsonare covered.bun run: in ES module output a file that is onlymodule.exports = require("./data.json")is linked as the data file. Main already gives the whole object for an import of it when nothing else requires the data file. With--format=cjs, or with a second statement in the file, it is a CommonJS module and keeps5.onLoadplugin returns. A result withloader: "object"is the exports of a module, andbun rungivesexports.defaultfor it. It reaches the linker as JSON, so the linker cannot tell it from JSON text that a plugin returns. That text keeps5too. Bun.build: bind default import to exports.default for loader: "object" plugins #36401 is open on theloader: "object"contract.require()that the parser turns into an import for a package on the CommonJS unwrap list. That isrequire("react/data.json"), andmodule.exports = require("./data.json")in a file of such a package.require()of that file gives5for.default, as Node does. bundler: skip __toESM for an unwrapped require() of a package that keeps its CommonJS wrapper #46215 is open on the value of these calls.xmlloader (a document has one root element, so its value has one key), a.nodeaddon, a CSS module, an HTML import,sqlite, and the string loaders (text,file,md,wasm,base64,dataurl). A string gives the same namespace in both modes. 10 probes (an empty.htmlfile, two server HTML imports, a CSS module, a.nodefile, a text file, an XML file and an empty.cjsfile, each with arequire()or animport()) are byte-identical to main.import json from "./data.json"left external under--format=cjsstill prints__toESM(require("./data.json")). WithisNodeModethere, a plain{ "a": 1 }reads as{ "a": 1, "default": { "a": 1 } }underbunwhen the file was imported as an ES module first, becauserequire()then returns the module namespace (Share one value between import and require() of a data file, per loader #35973). The dev server format is not changed.default, for exampleObject.keys(ns)andns.__esModuleofimport * as ns.Question for a maintainer: is a data file a value in every bundle shape, and should that include the one-statement
module.exports = require()file? If that file must keep5, the record that the redirect points at the data file needs a marker.Measurements
Release builds with LTO, Linux x64: main 179664e against this PR at 840dd23. The commit after it edits comments and splits one condition into two locals.
--minifyand--format=cjs)cmp)import json from "./data.json"plusrequire("./data.json")(wc -c).jsfilenew WeakMapat start-up, bundle with a default import of a CommonJS module and an import of a data filedefinePropertyandbindcalls at start-up for that reprobun buildinstructions:u, 2,000 CommonJS modules (median of 9, interleaved)bun buildinstructions:u, 5,000 ES modulesbun buildinstructions:u, 500 data files imported and requiredtext(size)ImportRecordFlagsbits in useTests
bun bd test test/bundler/bundler_loader.test.ts: 95 pass. The 33 new cases fail on a build of main.bundler_cjs62 pass,bundler_cjs2esm113,bundler_plugin68,esbuild/loader10,bundler_npm2,bundler_dynamic_import_dce333.test/bundler/(108 files): 7,812 pass. Two results fail with and without this change in this container:bundler_bytecode_portable"encoder output is identical on every platform" (the same hash on both builds) and itslibraries.jscase.test/internal/source-lints: 183 pass.Self-review
The first shape of this change also bound a default-only import to
require_data()with no__toESMcall, and printed({ default: require_data() })for animport()that reads onlydefault. The review said to cut it to the record flag, and this PR is that cut. What the review found in the larger shape:.htmlfile, the server HTML import, a CSS module and an empty.jsfile also have. Without the__toESMimport, a bundle of an empty.htmlimport threwReferenceError: __commonJS is not defined, and a server HTML import gave two different outputs across builds. The test is now the loader, with a match that lists every loader.5for some importers before 1.4.1.loader: "object"andmodule.exports = require()shapes, which the first body did not name.Not done, as a follow-up if it is wanted: skip the
__toESMcall where an importer reads onlydefault. Measured on that shape: the repro goes from 1,613 to 445 bytes, and a default import plusrequire()of a 10,000-key JSON goes from 10,001definePropertycalls at start-up to 0. The 2 concerns not addressed here ask for a wider key for that skip.Related open PRs that touch the same lines: #46215 and #46386 (the unwrap-list
require()), #41953 and #46294 (print_to_esm_suffix). Bit ofTO_ESM_NODE_MODEinImportRecordFlags: 12 open PRs add a flag at1 << 19(2026-10-26), and one of them lands first and keeps that bit. This PR takes1 << 25at its next push. Check first that main and no other open PR use that bit by then. Two different flags with one bit compile with no error and no warning, and each then reads as the other.