Skip to content

fix(bun-plugin): run CommonJS under the Bun runtime and compile every source kind - #984

Open
owjs3901 wants to merge 7 commits into
mainfrom
fix/bun-runtime-commonjs
Open

owjs3901 wants to merge 7 commits into
mainfrom
fix/bun-runtime-commonjs

Conversation

@owjs3901

@owjs3901 owjs3901 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Under the Bun runtime, the Bun plugin now compiles every source kind (.ts, .mts, .cts, .tsx, .jsx, .mjs, .js, .cjs), and CommonJS keeps its exports for require() and import.

What Bun does (1.4.4, checked against real runs)

  • A runtime onLoad must return contents: undefined/null throws onLoad() expects an object returned, and {} or { loader } throws Expected "contents" to be a string. A file can't be handed back to Bun.
  • Bun reads returned contents as an ES module. For CommonJS it builds the CommonJS function wrapper but never calls it: console.log in a returned module.exports = … never prints, and require() and import both see {}. This happens with loader: 'js' and 'ts', with any extension (.cjs, .cts, .js, .ts), and with the // @bun @bun-cjs pragma. Bun does not detect CommonJS by syntax here.
  • loader: 'object' with exports works, but it can't run the module, require() can't return a function, and import gets no default.
  • An async onLoad makes require() fail: require() async module "…" is unsupported. Main's onLoad is async, so require() of any compiled file fails today.
  • What does work is an ES module that exports a binding as "module.exports". require() returns that value, including functions and primitives.
  • Natively, Bun runs a CommonJS module when it is loaded, before the ES modules that import it.
  • Mixing import with module.exports is rejected natively too (Cannot use import statement with CommonJS-only features). .cjs/.cts files that use ES module syntax are ES modules.
  • Bun.build bundles returned CommonJS correctly, including mixed output. Only the runtime has the problem.

Approach

New src/commonjs.ts. It only runs under the runtime; Bun.build is unchanged.

  1. A file is treated as CommonJS when it isn't .mjs/.mts/.jsx/.tsx, it is .cjs/.cts or mentions module/exports/export =, and, after Devup extraction and TypeScript stripping, it has no import/export statement.

  2. The stylesheet import the extractor adds is dropped, since it loads nothing under the runtime. TypeScript is stripped with Bun.Transpiler. Through define, __filename, __dirname and process.env.NODE_ENV stay live instead of being replaced by constants.

  3. The module runs in a CommonJS function through vm.runInThisContext. It gets exports, require (from createRequire), module, __filename, __dirname, and this === module.exports. It is registered in require.cache (Bun's pending entry for require(), a new Module for import), so a cycle gets the partial exports. A module that throws is removed from the cache. A file that doesn't compile as a script (top-level await, import.meta) is left to Bun as an ES module.

  4. Bun gets an ES module that exports module.exports three ways:

    • as "module.exports", which is what require() returns;
    • as default (exports.default when __esModule is set);
    • under each of its own names.

    That is the shape Bun gives CommonJS.

loadSourceFile is now synchronous, so require() works. The filter widens to .mts/.cts everywhere, and to .js/.cjs outside node_modules, inside @devup-ui packages and inside the packages listed in include (#925, merged). The .js/.cjs files of other packages in node_modules are still left to Bun.

Coordination

Test plan

  • commonjs-runtime.test.ts: a fresh Bun process (no repo preload) registers the plugin and loads each kind through it: .cjs, .cts with export =, .cts with module.exports, CommonJS .js, ES module .js, .mts, function exports, __esModule, a require cycle, and a .cjs with ES module syntax. It runs in both orders, require() then import and import then require(). It asserts the exact exports, require(x) === (await import(x)).default, this/__filename, and that every exported class is in the written stylesheet with its color.
  • plugin.test.ts: tests through the captured onLoad cover the generated ES module (functions, primitives, null, __esModule), TypeScript stripping keeping __dirname/NODE_ENV live, reloading, a throwing module leaving require.cache, syntax / top-level-await / ES module syntax left to Bun, .cjs/.mts/.cts ES modules, Bun.build bundling .cjs/.cts with CSS, and real require()/import through the preloaded plugin.
  • Included CommonJS library: commonjs-runtime.test.ts also loads node_modules/cjs-lib/index.js (module.exports) with include: ['cjs-lib'] and checks its exports and its compiled class in the stylesheet; plugin.test.ts checks the same through the captured onLoad, plus the .cjs cases of the include filter.
  • bun test --coverage packages/bun-plugin: commonjs.ts and plugin.ts at 100% lines and functions.
  • Full bun test compared with main in the same checkout: no new failures. The remaining failures need package builds that weren't built locally, and they fail the same way on main.
  • __regression__ suite (preload race, worktree isolation, CSS emit, JSX pragmas): 10 pass.
  • bunx tsc --noEmit, prettier --single-quote --no-semi.

요약

Bun 런타임에서 Bun 플러그인이 모든 소스 종류(.ts, .mts, .cts, .tsx, .jsx, .mjs, .js, .cjs)를 컴파일하고, CommonJS도 require()와 import 모두에서 exports를 그대로 유지합니다.

Bun 동작 조사 결과 (1.4.4, 실제 실행으로 확인)

  • 런타임 onLoad는 반드시 contents를 반환해야 합니다. undefined/null을 반환하면 onLoad() expects an object returned, {}나 { loader }를 반환하면 Expected "contents" to be a string 오류가 납니다. 파일을 Bun에 되돌려 줄 수 없습니다.
  • Bun은 반환된 contents를 ES 모듈로 읽습니다. CommonJS는 함수 래퍼로 감싸기만 하고 호출하지 않습니다. 반환한 module.exports = … 안의 console.log는 출력되지 않고, require()와 import 모두 {}를 받습니다. loader: 'js'/'ts', 모든 확장자(.cjs, .cts, .js, .ts), // @bun @bun-cjs 프라그마에서 모두 같습니다. 문법으로 CommonJS를 감지하지 않습니다.
  • loader: 'object' + exports는 동작하지만 모듈을 실행할 수 없고, require()가 함수를 반환할 수 없으며, import에 default가 없습니다.
  • onLoad가 async이면 require()가 실패합니다(require() async module "…" is unsupported). main의 onLoad가 async라서, 지금은 컴파일되는 모든 파일의 require()가 실패합니다.
  • 바인딩을 "module.exports"라는 이름으로 export하는 ES 모듈은 동작합니다. require()가 그 값을 그대로 반환하고, 함수와 원시값도 마찬가지입니다.
  • Bun은 CommonJS 모듈을 로드 시점에, 그것을 import하는 ES 모듈보다 먼저 실행합니다.
  • import와 module.exports를 섞으면 네이티브에서도 오류입니다(Cannot use import statement with CommonJS-only features). ES 모듈 문법을 쓰는 .cjs/.cts는 ES 모듈로 취급됩니다.
  • Bun.build는 반환된 CommonJS(섞인 출력 포함)를 정상적으로 번들합니다. 문제는 런타임에만 있습니다.

접근

src/commonjs.ts를 새로 추가했습니다. 런타임에서만 동작하고 Bun.build는 바뀌지 않습니다.

  1. 다음 조건을 모두 만족하는 파일을 CommonJS로 봅니다. .mjs/.mts/.jsx/.tsx가 아니고, .cjs/.cts이거나 module/exports/export =를 쓰며, Devup 추출과 TypeScript 제거 뒤에 import/export 문이 없어야 합니다.

  2. 추출기가 넣는 스타일시트 import는 런타임에서 아무것도 로드하지 않으므로 제거합니다. TypeScript는 Bun.Transpiler로 제거합니다. 이때 define으로 __filename, __dirname, process.env.NODE_ENV가 상수로 바뀌지 않고 실행 시점의 값을 쓰게 합니다.

  3. 모듈은 vm.runInThisContext를 통해 CommonJS 함수로 실행합니다. exports, require(createRequire로 생성), module, __filename, __dirname을 넘기고 this === module.exports입니다. 모듈은 require.cache에 등록되므로(require()일 때는 Bun이 미리 만든 항목, import일 때는 새 Module) 순환 참조는 부분 exports를 받습니다. 예외를 던진 모듈은 캐시에서 제거합니다. 스크립트로 컴파일되지 않는 파일(top-level await, import.meta)은 ES 모듈로 Bun에 맡깁니다.

  4. Bun에는 module.exports를 세 가지로 export하는 ES 모듈을 넘깁니다.

    • "module.exports": require()가 반환하는 값입니다.
    • default: __esModule이 설정되어 있으면 exports.default입니다.
    • 각자의 이름으로 된 named export.

    Bun이 CommonJS를 노출하는 형태와 같습니다.

loadSourceFile을 동기로 바꿔서 require()가 동작합니다. 필터는 .mts/.cts를 모든 위치로, .js/.cjs를 node_modules 밖, @devup-ui 패키지 안, include에 나열한 패키지 안(#925, 머지됨)으로 넓혔습니다. 다른 패키지의 node_modules 안 .js/.cjs는 계속 Bun에 맡깁니다.

조율

  • fix(plugins): compile modern modules, resolve bundler conditions and hoist over every source root #934 (fix/plugin-core-update): 이 PR로 module.exports / export =로 작성한 .cts가 런타임에서 동작합니다. 따라서 #934는 bun-plugin README와 limitations 페이지의 .cts 주의 문구를 뺄 수 있습니다. sourceLoader 헬퍼와 .mts/.cts 필터가 겹칩니다. 리베이스할 때 withDependencyImports가 런타임의 CommonJS에 import 문을 덧붙이면 안 됩니다. import가 붙으면 출력이 다시 ES 모듈이 되어 exports를 잃습니다. commonJsSource가 처리하는 파일에서는 건너뛰거나 require()를 쓰면 됩니다.
  • fix(bun-plugin): compile the .js files of included packages #925 (머지됨): main 머지에서 해결했습니다. createSourceFilter가 @devup-ui와 include 이름을 .js/.cjs를 받는 하나의 node_modules 분기로 묶어, include 패키지의 파일도 같은 loadSourceFile → commonJsSource 경로를 거칩니다. 따라서 include의 CommonJS 라이브러리도 런타임에서 exports를 유지합니다. README의 "ES 모듈을 배포하는 패키지만 나열" 문구는 삭제했습니다.

테스트 계획

  • commonjs-runtime.test.ts: 레포 preload가 없는 새 Bun 프로세스에서 플러그인을 등록하고 다음 파일을 로드합니다. .cjs, export =를 쓰는 .cts, module.exports를 쓰는 .cts, CommonJS .js, ES 모듈 .js, .mts, 함수 export, __esModule, require 순환 참조, ES 모듈 문법을 쓰는 .cjs. require()를 먼저 하는 순서와 import를 먼저 하는 순서 두 가지로 실행합니다. 정확한 exports, require(x) === (await import(x)).default, this/__filename, 그리고 export된 모든 클래스가 작성된 스타일시트에 해당 색과 함께 있는지 확인합니다.
  • plugin.test.ts: 캡처한 onLoad를 통해 다음을 검증합니다. 생성된 ES 모듈(함수, 원시값, null, __esModule), TypeScript 제거 후에도 __dirname/NODE_ENV가 실행 시점 값인지, 재로드, 예외를 던진 모듈의 require.cache 제거, 문법 오류 / top-level await / ES 모듈 문법을 Bun에 맡기는지, ES 모듈인 .cjs/.mts/.cts, Bun.build의 .cjs/.cts 번들과 CSS, preload된 플러그인을 통한 실제 require()/import.
  • include된 CommonJS 라이브러리: commonjs-runtime.test.ts가 include: ['cjs-lib']로 node_modules/cjs-lib/index.js(module.exports)도 로드해 exports와 스타일시트의 컴파일된 클래스를 확인합니다. plugin.test.ts는 캡처한 onLoad와 include 필터의 .cjs 케이스로 같은 내용을 확인합니다.
  • bun test --coverage packages/bun-plugin: commonjs.ts와 plugin.ts 모두 라인·함수 커버리지 100%.
  • 같은 체크아웃에서 전체 bun test를 main과 비교: 새 실패 없음. 남은 실패는 로컬에서 빌드하지 않은 패키지 빌드가 필요한 테스트이며, main에서도 같은 이유로 실패합니다.
  • __regression__ 스위트(preload race, worktree isolation, CSS emit, JSX pragmas): 10개 통과.
  • bunx tsc --noEmit, prettier --single-quote --no-semi.

Refs #686

🤖 Generated with Claude Code

owjs3901 and others added 7 commits November 17, 2026 12:32
… source kind

Bun reads the contents a runtime onLoad callback returns as an ES module. For
CommonJS it builds the CommonJS wrapper but never calls it, so the module body
does not run and require() and import see {} (Bun 1.4.4). Returning no contents
is an error, and no loader (js, ts, object) or namespace keeps CommonJS
semantics, so the runtime plugin now runs a CommonJS module itself: Devup UI
compiles it, Bun's transpiler strips TypeScript, and the module runs in a
CommonJS function with its own require, module, __filename and __dirname,
registered in require.cache for cycles. Bun gets an ES module that exports
module.exports as "module.exports" (what require() returns), as default
(exports.default under __esModule) and by name, as Bun exports CommonJS.

The filter now covers .mts and .cts everywhere, and .js and .cjs outside
node_modules and in @devup-ui packages. Source loads are synchronous, since Bun
cannot require() a module whose onLoad is async. Bun.build is unchanged: it
bundles the CommonJS it is handed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lint forbids require() imports; createRequire goes through the same
Bun loader and plugin, so the test still checks the CommonJS exports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolve the onLoad filter against #925: createSourceFilter now loads .js
and .cjs outside node_modules and of @devup-ui and the include packages,
so an included CommonJS library goes through loadSourceFile and
commonJsSource under the runtime and keeps its exports. Add a runtime test
for an included CommonJS package and merge the README texts, dropping the
ES-modules-only caveat for include packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bundle the Bun.build CommonJS test imported in-process landed in the
root coverage report at 82% lines (Bun's unused CommonJS interop helpers)
and failed the 100% threshold. Import it in a child process instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolve the limitations page against main: keep main's new ThemeProvider
:root note and this branch's Bun plugin note (every source kind, ES modules
and CommonJS, and the .js/.cjs of @devup-ui and include packages), which
replaces main's older ".js only inside @devup-ui" text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pick up #990, which fixes main's rsbuild hook-order and WASM ABI count
tests, so the publish job runs without those known failures. No conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolve against #962: the synchronous loadSourceFile now takes the
BunProject, so the CommonJS runtime path extracts with the project's
cssDir, importAliases and compiledPackages (the stylesheet import it drops
is the one made from that cssDir) instead of module-level paths. Keep both
the CommonJS and the project-root test suites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant