Repository navigation
Conversation
… 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>
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.
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 forrequire()andimport.What Bun does (1.4.4, checked against real runs)
onLoadmust return contents:undefined/nullthrowsonLoad() expects an object returned, and{}or{ loader }throwsExpected "contents" to be a string. A file can't be handed back to Bun.console.login a returnedmodule.exports = …never prints, andrequire()andimportboth see{}. This happens withloader: 'js'and'ts', with any extension (.cjs,.cts,.js,.ts), and with the// @bun @bun-cjspragma. Bun does not detect CommonJS by syntax here.loader: 'object'withexportsworks, but it can't run the module,require()can't return a function, andimportgets nodefault.asynconLoadmakesrequire()fail:require() async module "…" is unsupported. Main'sonLoadis async, sorequire()of any compiled file fails today."module.exports".require()returns that value, including functions and primitives.importwithmodule.exportsis rejected natively too (Cannot use import statement with CommonJS-only features)..cjs/.ctsfiles that use ES module syntax are ES modules.Bun.buildbundles returned CommonJS correctly, including mixed output. Only the runtime has the problem.Approach
New
src/commonjs.ts. It only runs under the runtime;Bun.buildis unchanged.A file is treated as CommonJS when it isn't
.mjs/.mts/.jsx/.tsx, it is.cjs/.ctsor mentionsmodule/exports/export =, and, after Devup extraction and TypeScript stripping, it has noimport/exportstatement.The stylesheet import the extractor adds is dropped, since it loads nothing under the runtime. TypeScript is stripped with
Bun.Transpiler. Throughdefine,__filename,__dirnameandprocess.env.NODE_ENVstay live instead of being replaced by constants.The module runs in a CommonJS function through
vm.runInThisContext. It getsexports,require(fromcreateRequire),module,__filename,__dirname, andthis === module.exports. It is registered inrequire.cache(Bun's pending entry forrequire(), a newModuleforimport), 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.Bun gets an ES module that exports
module.exportsthree ways:"module.exports", which is whatrequire()returns;default(exports.defaultwhen__esModuleis set);That is the shape Bun gives CommonJS.
loadSourceFileis now synchronous, sorequire()works. The filter widens to.mts/.ctseverywhere, and to.js/.cjsoutsidenode_modules, inside@devup-uipackages and inside the packages listed ininclude(#925, merged). The.js/.cjsfiles of other packages innode_modulesare still left to Bun.Coordination
fix/plugin-core-update): with this PR,.ctswritten withmodule.exports/export =works under the runtime, so fix(plugins): compile modern modules, resolve bundler conditions and hoist over every source root #934 can drop the.ctscaveat from the bun-plugin README and the limitations page. ThesourceLoaderhelper and the.mts/.ctsfilter overlap. On rebase,withDependencyImportsmust not appendimportstatements to CommonJS under the runtime: animportmakes the output an ES module again and loses the exports. Skip it, or userequire(), whencommonJsSourcetakes the file.createSourceFilterputs@devup-uiand theincludenames in onenode_modulesbranch that accepts.jsand.cjs, so an included package's files go through the sameloadSourceFile→commonJsSourcepath and CommonJS libraries inincludekeep their exports under the runtime. The README's "list only packages that publish ES modules" note is gone.Test plan
commonjs-runtime.test.ts: a fresh Bun process (no repo preload) registers the plugin and loads each kind through it:.cjs,.ctswithexport =,.ctswithmodule.exports, CommonJS.js, ES module.js,.mts, function exports,__esModule, arequirecycle, and a.cjswith ES module syntax. It runs in both orders,require()thenimportandimportthenrequire(). 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 capturedonLoadcover the generated ES module (functions, primitives,null,__esModule), TypeScript stripping keeping__dirname/NODE_ENVlive, reloading, a throwing module leavingrequire.cache, syntax / top-level-await / ES module syntax left to Bun,.cjs/.mts/.ctsES modules,Bun.buildbundling.cjs/.ctswith CSS, and realrequire()/importthrough the preloaded plugin.commonjs-runtime.test.tsalso loadsnode_modules/cjs-lib/index.js(module.exports) withinclude: ['cjs-lib']and checks its exports and its compiled class in the stylesheet;plugin.test.tschecks the same through the capturedonLoad, plus the.cjscases of the include filter.bun test --coverage packages/bun-plugin:commonjs.tsandplugin.tsat 100% lines and functions.bun testcompared 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에 되돌려 줄 수 없습니다.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()가 그 값을 그대로 반환하고, 함수와 원시값도 마찬가지입니다.import와module.exports를 섞으면 네이티브에서도 오류입니다(Cannot use import statement with CommonJS-only features). ES 모듈 문법을 쓰는.cjs/.cts는 ES 모듈로 취급됩니다.Bun.build는 반환된 CommonJS(섞인 출력 포함)를 정상적으로 번들합니다. 문제는 런타임에만 있습니다.접근
src/commonjs.ts를 새로 추가했습니다. 런타임에서만 동작하고Bun.build는 바뀌지 않습니다.다음 조건을 모두 만족하는 파일을 CommonJS로 봅니다.
.mjs/.mts/.jsx/.tsx가 아니고,.cjs/.cts이거나module/exports/export =를 쓰며, Devup 추출과 TypeScript 제거 뒤에import/export문이 없어야 합니다.추출기가 넣는 스타일시트 import는 런타임에서 아무것도 로드하지 않으므로 제거합니다. TypeScript는
Bun.Transpiler로 제거합니다. 이때define으로__filename,__dirname,process.env.NODE_ENV가 상수로 바뀌지 않고 실행 시점의 값을 쓰게 합니다.모듈은
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에 맡깁니다.Bun에는
module.exports를 세 가지로 export하는 ES 모듈을 넘깁니다."module.exports":require()가 반환하는 값입니다.default:__esModule이 설정되어 있으면exports.default입니다.Bun이 CommonJS를 노출하는 형태와 같습니다.
loadSourceFile을 동기로 바꿔서require()가 동작합니다. 필터는.mts/.cts를 모든 위치로,.js/.cjs를node_modules밖,@devup-ui패키지 안,include에 나열한 패키지 안(#925, 머지됨)으로 넓혔습니다. 다른 패키지의node_modules안.js/.cjs는 계속 Bun에 맡깁니다.조율
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()를 쓰면 됩니다.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.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