Skip to content

bundler: skip the CommonJS unwrap list for require() of a .json specifier on node and bun targets - #46386

Open
robobun wants to merge 9 commits into
mainfrom
robobun/906fb844/json-require-stays-require
Open

robobun wants to merge 9 commits into
mainfrom
robobun/906fb844/json-require-stays-require

Conversation

@robobun

@robobun robobun commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • bun build --target=node --external react prints require("react/package.json") as import * as pkg from "react/package.json". Node throws TypeError [ERR_IMPORT_ATTRIBUTE_MISSING]: Module ".../react/package.json" needs an import attribute of "type: json".
  • Bundled, the whole value is wrong: Object.keys(pkg) gains default, and a write fails the build.
  • Cause: transpose_require (src/js_parser/p.rs:1631) unwraps by package name only.

Fix

  • In node and bun code, require() of a .json specifier stays a require(). A package off the list gets that.
  • Browser code behaves as on main.
  • Verified: test/bundler/bundler_cjs2esm.test.ts (26 new cases, 21 fail on main, 6 run in Node). 280 React builds stay byte-identical.
  • Self-reviewed: 23 concerns raised, 21 addressed, 2 in part (Notes).

Background

  • Unwrap list: in ESM output, require() of react and 6 more package names becomes import * as ns.
  • No user reported this. @frontegg/react reaches the Node error. bun compile --library defaults to this case (Notes).
  • A maintainer can choose this instead (Notes): no unwrap list on node and bun. One line, 3 to 5 % more bytes in production React builds.

Downsides

  • Four shapes that load on main fail on node and bun (Notes). The largest: a second bundler no longer inlines an external react/package.json.
  • One build can give the parsed value in a server chunk and the namespace in its page chunk.
  • On node, a minified bundled pkg.version read grows from 31 B to 906 B. An unwrapped JavaScript require() costs 74 more instructions.
Notes

Reach. No user report exists. The unwrap list dates from e05cc8d and the package-name test in transposeRequire from 06dab24 (both 2023-04-16, first in bun-v0.6.0). On the tracker, ERR_IMPORT_ATTRIBUTE_MISSING matches no issue and two PRs (#40836, #35914). The older code ERR_IMPORT_ASSERTION_TYPE_MISSING matches #4257 (closed), which is about a user-written import assertion. #46072 lists this case under "What stays as on main".

Uses that I checked:

  • @frontegg/react 7.19.0, CommonJS only. index.js:7 is var React = require('react'); and index.js:15 is var ReactPkg = _interopDefault(require('react/package.json'));. An application bundle for Node reaches the error through it.
  • @parcel/runtime-react-refresh 2.13.3, lib/ReactRefreshRuntime.js:21. It is a Parcel runtime.
  • bun compile --library builds for node with the peer dependencies external. A library with react as a peer dependency and a require("react/package.json") gets a dist/index.js that Node refuses on main. With this PR Node loads it.

Workaround on released versions. Put the require() in a try body (try { var pkg = require("react/package.json"); } finally {}), or build with --format=cjs. Both print react 18.3.1 under Node on 1.4.3 and on main. This does not reach a third-party package in the bundle, and the build exits 0, so nothing says that a workaround is necessary.

Before and after (bun build entry.js --target=node --external react, then node out.mjs)

// main: TypeError [ERR_IMPORT_ATTRIBUTE_MISSING]
import * as pkg from "react/package.json";
console.log(pkg.name, pkg.version);

// this PR: react 18.3.1
import { createRequire } from "node:module";
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __require = /* @__PURE__ */ createRequire(import.meta.url);
var require_entry = __commonJS(function() {
  var pkg = __require("react/package.json");
  console.log(pkg.name, pkg.version);
});
export default require_entry();

A read of pkg.version through a variable, by target and delivery (main, then this PR)

Target Package bundled Package external
node right, right (31 B to 906 B) Node error, right
bun right, right (39 B to 914 B) right, right
browser no change no change

Other uses of the value, with React 18.3.1:

  • The whole value is wrong on main in every bundled cell. Object.keys(require("react/package.json")).length is 15 on main. It is 14 in Node, with --format=cjs, and with this PR on node and bun. In browser code it stays 15.
  • A write (pkg.extra = 1) is the build error Cannot assign to import "extra" on main. With this PR it builds on node and bun, and the next require() sees the write.
  • A destructuring declaration (const { name } = require("react/package.json")) with the package external throws ReferenceError: __require is not defined on main for bun and browser. It runs there only if another run-time require() is in the bundle (the defect of bundler: read the import namespace for a destructured require() of an unwrapped package #46072). With this PR it runs on node and bun. On browser it still throws.
  • A JSON array or a default key shows the same defect (Array.isArray is false, .default is the whole object). No listed package ships such a file, so those need an alias or a first-party package with a listed name.

The first three are why bun is in the rule, although the table shows no error there.

What changes for a .json require of a listed package on node and bun. A package off the list already behaves this way on main.

  • The record is a require: require-call in onResolve and the metafile, and the require condition of an exports map.
  • A file whose only imports are such requires is CommonJS: a __commonJS wrapper, a default export on an entry chunk, and format: "cjs" in the metafile (main: esm).
  • The load happens at the call. A require() in a function that never runs loads nothing. A call whose result is unused still loads.

The rule is per file, not per build. Runtime::Features::target_has_require is set from the target of the transpiler that parses the file (topts.target, src/bundler/ParseTask.rs:2281).

  • In a node or bun build with an HTML import, the files that the page reaches are browser code and keep main's output. With one file that both graphs require (bun build server.js --target=bun --outdir out), main gives 15 keys in the server chunk and 15 in the page chunk. This PR gives 14 and 15. A read of one key agrees in both.
  • A write in such a file still fails the build, with one Cannot assign to import "extra" error from the browser graph.
  • The page chunk of such a build gains one unused line, var __commonJS = ... (2698 B to 2798 B), and a new hash in its name. When only the page requires the file, its chunk is byte-identical to main.
  • A #!/usr/bin/env bun first line gives the entry point the bun parse target. The __require helper follows the build target, and the browser helper throws. So the flag does not read the hashbang, and that entry point of a browser build is byte-identical to main.

Why browser code does not change. Until 2026-11-18 this PR applied the rule to every target. Measured with that revision on 2026-10-21:

  • @frontegg/react 7.19.0 built with the default target and --external react --external react-dom: main prints import * as _package from "react/package.json". A browser rejects that import, and an esbuild 0.21.5 bundle of the output loads. That revision printed one __require("react/package.json") call, and the esbuild bundle threw Dynamic require of "react/package.json" is not supported.
  • An HTML <script src> whose only import is such a require() became CommonJS. An HTML entry point never calls a wrapped script, so the script no longer ran.
  • A bundled pkg.version read grew from 31 B to 906 B.

The four shapes in Downsides. Each loads on main and fails with this PR on node and bun. Browser code is as on main.

  1. A second bundler. An app with @frontegg/react 7.19.0, built with bun build app.js --target=node --external react --external react-dom, then bundled again with React inlined, then run with no node_modules.
    • Main: Node refuses the first output. The second bundle loads (esbuild 0.25.1, Rollup 4.68.7, rolldown 1.3.3, webpack 5.112.2, a second bun build), because the static import is inlined.
    • This PR: Node loads the first output. The second bundle keeps the createRequire call: Cannot find module 'react/package.json' with esbuild --format=esm, Rollup, rolldown and a second bun build, and ERR_INVALID_ARG_VALUE with esbuild's default CommonJS output. webpack loads. bun build --compile of the --target=bun output fails the same way.
    • --format=cjs in the first build is byte-identical to main and loads in every row. A package off the list already prints this call.
  2. A destructured require("react") next to a use of react/package.json in one chunk: const { version } = require("react/package.json"); const { createElement } = require("react");. Main and this PR print the same line, var { createElement } = __toESM((exports)); (the defect of bundler: read the import namespace for a destructured require() of an unwrapped package #46072). On main exports binds by accident to the top-level variable of the JSON file's exports key. The bundle loads, createElement is undefined, and the output prints 18.3.1 undefined. Here the JSON file is inside __commonJS(...), and the line throws ReferenceError: exports is not defined at load, as main does without the .json line.
  3. An unused .json require in TypeScript: import pkg = require("react/package.json") with no value use. Main prints no reference to the file (32 B). Here the call stays, as for a package off the list (1423 B bundled). With the package external and not installed, the output throws Cannot find module 'react/package.json'. Bundled and not installed, the build fails with Could not resolve: "react/package.json".
  4. The same JSON file required again through a destructured, extensionless require(): const a = require("react/package.json"); const { name } = require("react/package");. It prints 2.0.0 react on main and throws ReferenceError: exports is not defined here, through the same line as shape 2. It needs a package with no exports map: React 18.3.1 does not resolve react/package. No use of this shape is known.

The .aot.ts file of --library and --dts. The build prints that file from the same output. So a kept require() of an external package puts createRequire(import.meta.url) in it. Some tsconfig files declare no ImportMeta.url, for example lib: ["esnext"] with types: []. Then the type check of the file fails with TS2339, and the build leaves the file out with a warning. A package off the list does the same on main. With the dom lib the file is written.

Measurements

With the final build against a build of main ca74e0f:

  • React matrix: 280 of 280 cells byte-identical (67,844,679 B). React and react-dom 18.3.1 and 19.3.1, 7 entries, production and development, --minify on and off, targets browser, bun and node, plus --external, --packages=external and --splitting. npm/ReactSSR stays at its pinned size.
  • Bundled .version read of react/package.json, minified: node 31 B to 906 B, bun 39 B to 914 B, browser 31 B with no change. The reported external entry on node: 91 B to 385 B. A use of the whole value on node: 2589 B to 1452 B.
  • 26 new itBundled cases: 21 fail on a debug build of main, 26 pass on the PR build. Five are controls that pass on both: format: "cjs", the browser target, the hashbang entry (cli and api), and react-dom/server.node. Six cases run their output in Node: the five external node cases and the external case with the @frontegg/react shape. 0 existing lines of the test file changed.
  • Each half of the flag has a case. With target (the hashbang-aware value) in place of topts.target, the two hashbang cases fail. With the flag overwritten in gdb to the build target, the page-script case fails.

With release builds of main ca74e0f and of this PR at b7cc19b. The later edits are one expression in ParseTask.rs and a merge of main, both outside the operand:

  • The operand ran 0 times for bun run, cjs, iife and off-list ESM requires. In the React 18.3.1 / 19.3.1 client builds with --target=node it ran 6 / 8 times. With --target=browser only the flag test ran, 6 times (gdb hit counts, debug build).
  • transpose_require, instructions per call (gdb stepi, third call): when the predicate fails before the operand, cjs 287 to 288, off-list ESM 353 to 353 and 465 to 464. For an unwrapped JavaScript require(): 1109 to 1183 on node, 1109 to 1148 on browser. For a .json specifier on node: 1440 to 686. Part of the increase is inlining: new_symbol is a call in the PR build and inline in the base build.
  • Release binary: -512 B .text. transpose_require 1899 + 1971 B to 1756 + 1756 B (size -A, nm -S). The stripped binary has the same size.
  • A bundled .version read for an off-list copy of the package is 908 B, and 866 B with --format=cjs.
  • Allocator calls for a build with one .json require of a listed package on node: 7383 to 7470. The same build for an off-list package: 7469. On browser: 7033 to 7033. For require("react"): 7383 to 7383 (gdb hit counts on the mimalloc entry points).

Left as on main. The defect is larger than .json: an unwrapped require() gives a namespace where module.exports is owed. This PR fixes one spelling of it, in node and bun code. It covers one of the two parser paths that turn a require() into an import. I ran each line below on the final build.

Bundled:

  • Browser code, as said above.
  • A data file reached without a .json suffix: the extensionless require("react/list"), and require("scheduler/data") where data.js is module.exports = require("./data.json").
  • Six more data suffixes that Bun loads: .jsonc, .json5, .toml, .yaml, .yml, .xml. Under a listed name they keep the namespace on node and bun. They are left out by choice. .json is the only data suffix that Node's require() loads. So it is the only one where a kept call is right both bundled and external. A kept call for an external TOML or YAML file makes Node run it as JavaScript ({}, exit 0). A bundled .txt file is { default: "..." } where a package off the list gives the string.
  • react-dom/server.node is the JavaScript file server.node.js. A test pins that it stays unwrapped.
  • typeof require("react-refresh/babel") is object where Node gives function.

External:

  • require("scheduler/unstable_mock"): Node throws ERR_MODULE_NOT_FOUND.
  • The redirect (src/js_parser/parse/parse_entry.rs:1709), for every package on and off the list: a one-statement file module.exports = require("x/package.json") that another file reads with import. On node the output is still import p from "x/package.json" and Node throws the same error. On bun the output is ... with { type: "jsx" } and Bun fails to parse the JSON file. --format=cjs avoids both. It is a second parser path with no package test. A rule there changes the output for every package, so it is not in this PR.
  • A user-written with { type: "json" } is dropped for targets other than Bun.
  • const { useState } = require("react") with react external: ReferenceError: __require is not defined on every target (bundler: read the import namespace for a destructured require() of an unwrapped package #46072).

Runtime: after an import of the same data file, require() returns the module namespace under bun run, for every package.

Earlier PRs for some of these lines (#46215, #45830, #40836, #35973) and for the HTML script (#42026) were closed as stale on 2026-11-17. #46072 and #42500 are open.

Alternatives not taken.

  • No unwrap list where require() exists: an empty list for a server-side target at src/bundler/ParseTask.rs:2308, with no flag and no operand. A listed package then behaves like any other package on node and bun, which removes the list-caused lines above there. Measured with a build of it: 150 of the 280 React matrix cells change. The production minified client and SSR builds grow 3.1 to 5.3 % (React 18.3.1 SSR on node: 80,820 B to 84,431 B). 3 of the 139 cases of the test file fail, one of them main's cjs2esm/ReactSpecificUnwrappingTargetIsExternal. On those targets it turns off what bundler: bind the default import of a lifted CommonJS module to its namespace #41162 and bundler: lift module.exports = require() after side effects in unwrapped packages to export * #41188 improved, so it needs a maintainer's agreement. It replaces this PR.
  • The same rule on every target. It also fixes the whole value in browser bundles, and it breaks the three browser cases above.
  • Keep every unwrapped require() a require until the linker knows the file. 55 sites decide on the record kind, and 34 of them change branch. REVIEW.md:66 asks for a maintainer's agreement first.
  • A rule in linker step 1 for a marked record whose bundled file is a data file. It can also fix the browser bundles, and it cannot reach an external record.
  • A linker rule for an external record only (should_remove_import_export_stmt, src/bundler/LinkerContext.rs:1557). It needs no parser flag. It leaves the bundled value and the write as on main, and it needs a mark on the record and the same suffix test.
  • Keep a require() of a package that the options mark external. It changes require("scheduler") too, which cjs2esm/ReactSpecificUnwrappingTargetIsExternal pins, and the parser cannot see an external that a plugin declares.

Self-review. The review of the target-gated revision raised 23 concerns. 21 are addressed: the flag now reads topts.target, the new cases named above, and the text of this description. Two are addressed in part:

  • No issue is opened for the module.exports = require() redirect. This description is the record.
  • No bun compile --library case is added. That flow uses the same bundler options as the new cases. What it adds is the type check of the .aot.ts file, which depends on the tsconfig.

Suites run with the debug build: bundler_cjs2esm (139 pass), bundler_npm, bundler_cjs, bundler_bun, bundler_html, html-import-manifest, bundler_loader, bundler_edgecase, bundler_splitting, esbuild/default and transpiler/react-compiler. All pass. Only linux-x64 was run.

…mmonJS unwrap list

In ESM output, require() of a package on the CommonJS unwrap list becomes
`import * as ns`. The decision looked at the package name only, so
require("react/package.json") was unwrapped too. With the package external
the import has no `with { type: "json" }` and Node rejects it. With the
package bundled the result is a module namespace object, not the parsed
value.

transpose_require now leaves a require() whose specifier ends in .json a
require(), as for every package that is not on the list.
@robobun

robobun commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:07 AM PT - Nov 19th, 2026

✅ @robobun, your commit 19a407bc872cb30c51806c499b839d77c83653e0 passed in Build #143056! 🎉


🧪   To try this PR locally:

bunx bun-pr 46386

That installs a local version of the PR into your bun-46386 executable, so you can run:

bun-46386 --bun

@robobun

robobun commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review. The rule now applies to node and bun code only. Browser code behaves as on main.

How I reproduced it (1.4.3 and main print the import):

mkdir -p node_modules/react
echo '{"name":"react","version":"19.3.1"}' > node_modules/react/package.json
echo 'const pkg = require("react/package.json"); console.log(pkg.name, pkg.version);' > entry.js
bun build entry.js --target=node --external react --outfile out.mjs && node out.mjs
# main: TypeError [ERR_IMPORT_ATTRIBUTE_MISSING]: Module ".../react/package.json" needs an import attribute of "type: json"
# this PR: react 19.3.1

The first spawn of node after a build can take more than the 5 s test
timeout. The cases keep their proof: each one fails without the fix.
Comment thread src/js_parser/p.rs Resolved
--target=browser has no require() at run time. There, a require() of a
.json specifier of a listed package is still unwrapped, as on main. The
node and bun targets keep the call.
A `#!/usr/bin/env bun` line gives the first entry point the bun parse
target, but the `__require` helper of a browser build still throws. The
flag now reads `topts.target`, so that entry point is unwrapped as on main.

Tests: the external node cases run their output in Node. New cases cover
a hashbang entry of a browser build, a server build with an HTML import,
a destructuring declaration on the bun target, an unused import-equals,
and a CommonJS file that requires a listed package and its package.json.
@robobun robobun changed the title bundler: keep require() of a .json specifier a require() under the CommonJS unwrap list bundler: skip the CommonJS unwrap list for require() of a .json specifier on node and bun targets Nov 19, 2026
Comment thread src/bundler/ParseTask.rs Resolved
@robobun
robobun marked this pull request as ready for review November 19, 2026 06:39

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment thread src/js_parser/p.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant