Repository navigation
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
Open
bundler: skip the CommonJS unwrap list for require() of a .json specifier on node and bun targets#46386robobun wants to merge 9 commits into
.json specifier on node and bun targets#46386robobun wants to merge 9 commits into
Conversation
…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.
Collaborator
Author
|
Updated 1:07 AM PT - Nov 19th, 2026
✅ @robobun, your commit 19a407bc872cb30c51806c499b839d77c83653e0 passed in 🧪 To try this PR locally: bunx bun-pr 46386That installs a local version of the PR into your bun-46386 --bun |
Collaborator
Author
|
Status: ready for review. The rule now applies to 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.
…-require-stays-require
…-require-stays-require
--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.
…-require-stays-require
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.
.json specifier a require() under the CommonJS unwrap list.json specifier on node and bun targets
robobun
marked this pull request as ready for review
November 19, 2026 06:39
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
bun build --target=node --external reactprintsrequire("react/package.json")asimport * as pkg from "react/package.json". Node throwsTypeError [ERR_IMPORT_ATTRIBUTE_MISSING]: Module ".../react/package.json" needs an import attribute of "type: json".Object.keys(pkg)gainsdefault, and a write fails the build.transpose_require(src/js_parser/p.rs:1631) unwraps by package name only.Fix
nodeandbuncode,require()of a.jsonspecifier stays arequire(). A package off the list gets that.test/bundler/bundler_cjs2esm.test.ts(26 new cases, 21 fail on main, 6 run in Node). 280 React builds stay byte-identical.Background
require()ofreactand 6 more package names becomesimport * as ns.@frontegg/reactreaches the Node error.bun compile --librarydefaults to this case (Notes).nodeandbun. One line, 3 to 5 % more bytes in production React builds.Downsides
nodeandbun(Notes). The largest: a second bundler no longer inlines an externalreact/package.json.node, a minified bundledpkg.versionread grows from 31 B to 906 B. An unwrapped JavaScriptrequire()costs 74 more instructions.Notes
Reach. No user report exists. The unwrap list dates from e05cc8d and the package-name test in
transposeRequirefrom 06dab24 (both 2023-04-16, first in bun-v0.6.0). On the tracker,ERR_IMPORT_ATTRIBUTE_MISSINGmatches no issue and two PRs (#40836, #35914). The older codeERR_IMPORT_ASSERTION_TYPE_MISSINGmatches #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/react7.19.0, CommonJS only.index.js:7isvar React = require('react');andindex.js:15isvar ReactPkg = _interopDefault(require('react/package.json'));. An application bundle for Node reaches the error through it.@parcel/runtime-react-refresh2.13.3,lib/ReactRefreshRuntime.js:21. It is a Parcel runtime.bun compile --librarybuilds fornodewith the peer dependencies external. A library with react as a peer dependency and arequire("react/package.json")gets adist/index.jsthat Node refuses on main. With this PR Node loads it.Workaround on released versions. Put the
require()in atrybody (try { var pkg = require("react/package.json"); } finally {}), or build with--format=cjs. Both printreact 18.3.1under 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, thennode out.mjs)A read of
pkg.versionthrough a variable, by target and delivery (main, then this PR)Other uses of the value, with React 18.3.1:
Object.keys(require("react/package.json")).lengthis 15 on main. It is 14 in Node, with--format=cjs, and with this PR onnodeandbun. In browser code it stays 15.pkg.extra = 1) is the build errorCannot assign to import "extra"on main. With this PR it builds onnodeandbun, and the nextrequire()sees the write.const { name } = require("react/package.json")) with the package external throwsReferenceError: __require is not definedon main forbunandbrowser. It runs there only if another run-timerequire()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 onnodeandbun. Onbrowserit still throws.defaultkey shows the same defect (Array.isArrayis false,.defaultis 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
bunis in the rule, although the table shows no error there.What changes for a
.jsonrequire of a listed package onnodeandbun. A package off the list already behaves this way on main.require-callinonResolveand the metafile, and therequirecondition of anexportsmap.__commonJSwrapper, adefaultexport on an entry chunk, andformat: "cjs"in the metafile (main:esm).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_requireis set from the target of the transpiler that parses the file (topts.target,src/bundler/ParseTask.rs:2281).nodeorbunbuild 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.Cannot assign to import "extra"error from the browser graph.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.#!/usr/bin/env bunfirst line gives the entry point thebunparse target. The__requirehelper 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/react7.19.0 built with the default target and--external react --external react-dom: main printsimport * 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 threwDynamic require of "react/package.json" is not supported.<script src>whose only import is such arequire()became CommonJS. An HTML entry point never calls a wrapped script, so the script no longer ran.pkg.versionread grew from 31 B to 906 B.The four shapes in Downsides. Each loads on main and fails with this PR on
nodeandbun. Browser code is as on main.@frontegg/react7.19.0, built withbun build app.js --target=node --external react --external react-dom, then bundled again with React inlined, then run with nonode_modules.bun build), because the static import is inlined.createRequirecall:Cannot find module 'react/package.json'with esbuild--format=esm, Rollup, rolldown and a secondbun build, andERR_INVALID_ARG_VALUEwith esbuild's default CommonJS output. webpack loads.bun build --compileof the--target=bunoutput fails the same way.--format=cjsin the first build is byte-identical to main and loads in every row. A package off the list already prints this call.require("react")next to a use ofreact/package.jsonin 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 mainexportsbinds by accident to the top-level variable of the JSON file'sexportskey. The bundle loads,createElementisundefined, and the output prints18.3.1 undefined. Here the JSON file is inside__commonJS(...), and the line throwsReferenceError: exports is not definedat load, as main does without the.jsonline..jsonrequire 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 throwsCannot find module 'react/package.json'. Bundled and not installed, the build fails withCould not resolve: "react/package.json".require():const a = require("react/package.json"); const { name } = require("react/package");. It prints2.0.0 reacton main and throwsReferenceError: exports is not definedhere, through the same line as shape 2. It needs a package with noexportsmap: React 18.3.1 does not resolvereact/package. No use of this shape is known.The
.aot.tsfile of--libraryand--dts. The build prints that file from the same output. So a keptrequire()of an external package putscreateRequire(import.meta.url)in it. Some tsconfig files declare noImportMeta.url, for examplelib: ["esnext"]withtypes: []. 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 thedomlib the file is written.Measurements
With the final build against a build of main ca74e0f:
--minifyon and off, targets browser, bun and node, plus--external,--packages=externaland--splitting.npm/ReactSSRstays at its pinned size..versionread ofreact/package.json, minified:node31 B to 906 B,bun39 B to 914 B,browser31 B with no change. The reported external entry onnode: 91 B to 385 B. A use of the whole value onnode: 2589 B to 1452 B.itBundledcases: 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 (cliandapi), andreact-dom/server.node. Six cases run their output in Node: the five externalnodecases and the external case with the@frontegg/reactshape. 0 existing lines of the test file changed.target(the hashbang-aware value) in place oftopts.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.rsand a merge of main, both outside the operand:bun run, cjs, iife and off-list ESM requires. In the React 18.3.1 / 19.3.1 client builds with--target=nodeit ran 6 / 8 times. With--target=browseronly 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 JavaScriptrequire(): 1109 to 1183 onnode, 1109 to 1148 onbrowser. For a.jsonspecifier onnode: 1440 to 686. Part of the increase is inlining:new_symbolis a call in the PR build and inline in the base build..text.transpose_require1899 + 1971 B to 1756 + 1756 B (size -A,nm -S). The stripped binary has the same size..versionread for an off-list copy of the package is 908 B, and 866 B with--format=cjs..jsonrequire of a listed package onnode: 7383 to 7470. The same build for an off-list package: 7469. Onbrowser: 7033 to 7033. Forrequire("react"): 7383 to 7383 (gdb hit counts on the mimalloc entry points).Left as on main. The defect is larger than
.json: an unwrappedrequire()gives a namespace wheremodule.exportsis owed. This PR fixes one spelling of it, innodeandbuncode. It covers one of the two parser paths that turn arequire()into an import. I ran each line below on the final build.Bundled:
.jsonsuffix: the extensionlessrequire("react/list"), andrequire("scheduler/data")wheredata.jsismodule.exports = require("./data.json")..jsonc,.json5,.toml,.yaml,.yml,.xml. Under a listed name they keep the namespace onnodeandbun. They are left out by choice..jsonis the only data suffix that Node'srequire()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.txtfile is{ default: "..." }where a package off the list gives the string.react-dom/server.nodeis the JavaScript fileserver.node.js. A test pins that it stays unwrapped.typeof require("react-refresh/babel")isobjectwhere Node givesfunction.External:
require("scheduler/unstable_mock"): Node throwsERR_MODULE_NOT_FOUND.src/js_parser/parse/parse_entry.rs:1709), for every package on and off the list: a one-statement filemodule.exports = require("x/package.json")that another file reads withimport. Onnodethe output is stillimport p from "x/package.json"and Node throws the same error. Onbunthe output is... with { type: "jsx" }and Bun fails to parse the JSON file.--format=cjsavoids 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.with { type: "json" }is dropped for targets other than Bun.const { useState } = require("react")with react external:ReferenceError: __require is not definedon every target (bundler: read the import namespace for a destructured require() of an unwrapped package #46072).Runtime: after an
importof the same data file,require()returns the module namespace underbun 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.
require()exists: an empty list for a server-side target atsrc/bundler/ParseTask.rs:2308, with no flag and no operand. A listed package then behaves like any other package onnodeandbun, 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 onnode: 80,820 B to 84,431 B). 3 of the 139 cases of the test file fail, one of them main'scjs2esm/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.require()a require until the linker knows the file. 55 sites decide on the record kind, and 34 of them change branch.REVIEW.md:66asks for a maintainer's agreement first.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.require()of a package that the options mark external. It changesrequire("scheduler")too, whichcjs2esm/ReactSpecificUnwrappingTargetIsExternalpins, 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:module.exports = require()redirect. This description is the record.bun compile --librarycase is added. That flow uses the same bundler options as the new cases. What it adds is the type check of the.aot.tsfile, 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/defaultandtranspiler/react-compiler. All pass. Only linux-x64 was run.