Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changepacks/changepack_log_bun_runtime_commonjs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"changes": {
"packages/bun-plugin/package.json": "Patch"
},
"note": "Compile every source kind under the Bun runtime: `.mts`, `.cts`, and `.js` and `.cjs` files outside `node_modules` join `.ts`, `.tsx`, `.jsx` and `.mjs`. CommonJS keeps its exports: Bun does not run CommonJS an `onLoad` callback returns, so the runtime plugin runs the module itself and hands Bun an ES module exporting its `module.exports` to `require()` and `import`. Source loads are synchronous, so `require()` works on compiled files too.",
"date": "2026-11-17T00:00:00.000Z"
}
2 changes: 1 addition & 1 deletion apps/landing/src/app/(detail)/docs/limitations/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ A dynamic value such as `width` becomes a CSS variable set in `style`, so a comp
- An `.mdx` file is extracted after your MDX plugin compiles it to JavaScript, never as raw MDX. The Vite (`@mdx-js/rollup`), webpack and Rsbuild (`@mdx-js/loader`, `@rsbuild/plugin-mdx`) plugins and Next.js with webpack (`@next/mdx`) run their MDX step in a later phase: Vite in a `post` transform, webpack and Rsbuild in a `post` loader. Next.js with Turbopack and the Bun plugin do not extract MDX yet. The scan that reserves class names before a build reads JavaScript and TypeScript modules only, so a document's own classes are named when it compiles. Put components that need Devup UI styles in a `.tsx` module and use them from the document.
- The plugins read `jsxImportSource` from the `tsconfig.json` (or `jsconfig.json`) in the working directory. Opt out with `importAliases: { '@emotion/react/jsx-runtime': false }`.
- The outermost `ThemeProvider` also declares its theme on `:root`, in a `<style>` element rendered before its `<div>`, so `createGlobalStyle` and `<Global>` rules on `html`, `body` or `:root` read it; a nested provider changes only its own subtree. Several outermost providers side by side all write `:root`, and the last one in the document wins there. The `<style>` element also counts in the `textContent` of what holds the provider.
- The Bun plugin compiles `.ts`, `.tsx`, `.jsx` and `.mjs` files, but `.js` files only inside `@devup-ui` packages: Devup UI code in a `.js` file of your own project reaches the runtime placeholders. Use `.jsx`, `.tsx` or `.mjs` for it. A Bun runtime plugin must return the source of every file it matches, and Bun reads that source as an ES module, so matching `.js` files would break CommonJS ones.
- The Bun plugin compiles `.ts`, `.mts`, `.cts`, `.tsx`, `.jsx`, `.mjs`, `.js` and `.cjs` files, ES modules and CommonJS alike, under the runtime as in `Bun.build`; `require()` and `import` keep the exports of a CommonJS module. Inside `node_modules` it compiles the `.js` and `.cjs` files of `@devup-ui` packages and of the packages listed in its `include` option only. A Bun runtime plugin must return the source of every file it matches, and Bun runs that source as an ES module, so under the runtime the plugin runs a CommonJS module itself and hands Bun an ES module that exports its `module.exports`.
- Code that only the runtime can compute — other globals, `Date`, `Math.random`, `new`, classes, async code — is never run by the build; on an element it stays a CSS variable, elsewhere it is a build error.

## Build errors
Expand Down
38 changes: 24 additions & 14 deletions packages/bun-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,21 +62,30 @@ Class names are short in `Bun.build` and readable under the runtime; pass

## Compiled Files

`.ts`, `.tsx`, `.jsx` and `.mjs` files are compiled wherever they are, and
`.js` files only inside `@devup-ui` packages and the packages you list in
`include`, as in the other plugins. Devup UI code in a `.js` file of your own
project is not compiled and reaches the runtime placeholders
(`Cannot run on the runtime`). Give such files a `.jsx`, `.tsx` or `.mjs`
extension.

The runtime cannot take those files on. A Bun runtime plugin must return the
source of every file its filter matches, it cannot hand a file back to Bun, and
Bun reads returned source as an ES module, so a CommonJS `.js` file
(`require`, `module.exports`) it matched would stop loading.
`.ts`, `.mts`, `.cts`, `.tsx`, `.jsx` and `.mjs` files are compiled wherever
they are, and `.js` and `.cjs` files outside `node_modules`, inside
`@devup-ui` packages and inside the packages you list in `include`, as in the
other plugins. The `.js` and `.cjs` files of other packages in `node_modules`
are left to Bun.

ES modules and CommonJS are both supported, under the runtime as in
`Bun.build`. A `.cjs`, `.cts` or `.js` file written with `require`,
`module.exports`, `exports.name` or `export =` keeps its exports for
`require()` and `import`.

A Bun runtime plugin must return the source of every file it matches, and Bun
runs returned source as an ES module: CommonJS returned as is would not run
and would export nothing. So under the runtime the plugin runs a CommonJS
module itself, when it is loaded, as Bun does, and hands Bun an ES module that
exports its `module.exports`. `require()` returns `module.exports`, and
`import` gets it as `default` (`exports.default` when `__esModule` is set)
along with its named exports. `.jsx` and `.tsx` files are ES modules, as Bun
reads them.

## Libraries

List a library that ships Devup UI components as compiled `.js` in `include`:
List a library that ships Devup UI components as compiled `.js` or `.cjs` in
`include`:

```ts
DevupUI({ include: ['my-design-system'] })
Expand All @@ -86,8 +95,9 @@ await register({ include: ['my-design-system'] })

Each name matches that whole package (`my-lib` is not `my-lib-extra` or
`@scope/my-lib`), including in pnpm and Bun stores, but not the dependencies
in its own `node_modules`. Under the runtime its `.js` files are read as ES
modules, as above, so list only packages that publish ES modules there.
in its own `node_modules`. Its files go through the same path as your own, so
a package that publishes ES modules or CommonJS keeps its exports under the
runtime as in `Bun.build`.

## Compiler Engine

Expand Down
45 changes: 45 additions & 0 deletions packages/bun-plugin/src/__tests__/commonjs-runtime.child.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Loads every source kind through the registered runtime plugin, in a fresh
// Bun process without the repository's test preload. Prints what `require()`
// and `import` return, and the stylesheet the plugin wrote.
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join } from 'node:path'

import { register } from '../plugin'

const [root, order, ...files] = process.argv.slice(2)
if (!root) throw new Error('Expected a fixture root')
const importFirst = order === 'import-first'
process.chdir(root)
await register({ engine: 'wasm', include: ['cjs-lib'] })

function describe(value: unknown): unknown {
if (typeof value === 'function') return { function: value() }
if (typeof value !== 'object' || value === null) return value
return Object.fromEntries(
Object.keys(value)
.sort()
.map((key) => [key, describe(Reflect.get(value, key))]),
)
}

const require = createRequire(join(root, 'entry.js'))
const results: Record<string, unknown> = {}
for (const file of files) {
const path = join(root, file)
let imported: Record<string, unknown> = {}
if (importFirst) imported = await import(path)
const required: unknown = require(path)
if (!importFirst) imported = await import(path)
results[file] = {
required: describe(required),
imported: describe({ ...imported }),
same: 'default' in imported && imported.default === required,
}
}
process.stdout.write(
JSON.stringify({
results,
css: readFileSync(join(root, 'df', 'devup-ui', 'devup-ui.css'), 'utf-8'),
}),
)
179 changes: 179 additions & 0 deletions packages/bun-plugin/src/__tests__/commonjs-runtime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'

import { afterAll, describe, expect, it } from 'bun:test'

// Every source kind, loaded through the runtime plugin in a fresh Bun process
const sources: Record<string, string> = {
'commonjs.cjs': `const { css } = require('@devup-ui/react')
module.exports = { cls: css({ color: '#010203' }), self: this === module.exports, file: require('node:path').basename(__filename) }
`,
'export-equals.cts': `import { css } from '@devup-ui/react'
const kind: string = 'export ='
export = { cls: css({ color: '#040506' }), kind }
`,
'module-exports.cts': `const { css } = require('@devup-ui/react')
module.exports = { cls: css({ color: '#070809' }) as string }
`,
'commonjs.js': `const react = require('@devup-ui/react')
exports.cls = react.css({ color: '#0A0B0C' })
exports.run = function () { return 'run' }
`,
'module.js': `import { css } from '@devup-ui/react'
export const cls = css({ color: '#0D0E0F' })
`,
'module.mts': `import { css } from '@devup-ui/react'
export const cls: string = css({ color: '#101112' })
`,
'function.cjs': `module.exports = function plain() { return 'plain' }
module.exports.extra = 1
`,
'interop.cjs': `Object.defineProperty(exports, '__esModule', { value: true })
exports.default = 'main'
exports.named = 'named'
`,
'cycle-a.cjs': `exports.early = 'early'
exports.seen = require('./cycle-b.cjs').seen
`,
'cycle-b.cjs': `exports.seen = require('./cycle-a.cjs').early
`,
'syntax.cjs': `export const kind = 'module syntax'
`,
// A CommonJS library the child lists in `include`
'node_modules/cjs-lib/index.js': `const { css } = require('@devup-ui/react')
module.exports = { cls: css({ color: '#131415' }), name: 'cjs-lib' }
`,
}
const files = Object.keys(sources).filter((file) => file !== 'cycle-b.cjs')
const colors = [
'010203',
'040506',
'070809',
'0A0B0C',
'0D0E0F',
'101112',
'131415',
]

const roots: string[] = []
afterAll(() => {
for (const root of roots) rmSync(root, { recursive: true, force: true })
})

function fixture() {
const root = mkdtempSync(join(tmpdir(), 'devup-bun-commonjs-'))
roots.push(root)
writeFileSync(join(root, 'bunfig.toml'), '')
writeFileSync(join(root, 'devup.json'), '{}')
for (const [file, source] of Object.entries(sources)) {
mkdirSync(dirname(join(root, file)), { recursive: true })
writeFileSync(join(root, file), source)
}
// The runtime stub a `require()` the extractor keeps loads
const react = join(root, 'node_modules', '@devup-ui', 'react')
mkdirSync(react, { recursive: true })
writeFileSync(
join(react, 'package.json'),
'{"name":"@devup-ui/react","main":"index.js"}',
)
writeFileSync(
join(react, 'index.js'),
"exports.css = () => { throw new Error('Cannot run on the runtime') }\n",
)
return root
}

interface Loaded {
required: unknown
imported: unknown
same: boolean
}

function run(root: string, order: string) {
const child = Bun.spawnSync(
[
process.execPath,
join(import.meta.dir, 'commonjs-runtime.child.ts'),
root,
order,
...files,
],
{
cwd: root,
stdout: 'pipe',
stderr: 'pipe',
timeout: 30000,
env: { ...process.env, BUN_RUNTIME_TRANSPILER_CACHE_PATH: '0' },
},
)
expect(child.stderr.toString()).toBe('')
expect(child.exitCode).toBe(0)
const output: { results: Record<string, Loaded>; css: string } = JSON.parse(
child.stdout.toString(),
)
return output
}

/** What Bun gives for a CommonJS module that exports `value` */
function commonJs(value: Record<string, unknown>): Loaded {
return {
required: value,
imported: { ...value, default: value, 'module.exports': value },
same: true,
}
}

const styled = { cls: expect.any(String) }

describe.each(['require-first', 'import-first'])('Bun runtime, %s', (order) => {
it('keeps the exports of every source kind and compiles their styles', () => {
const { results, css } = run(fixture(), order)
expect(results).toEqual({
'commonjs.cjs': commonJs({ ...styled, self: true, file: 'commonjs.cjs' }),
'export-equals.cts': commonJs({ ...styled, kind: 'export =' }),
'module-exports.cts': commonJs(styled),
'commonjs.js': commonJs({ ...styled, run: { function: 'run' } }),
'module.js': { required: styled, imported: styled, same: false },
'module.mts': { required: styled, imported: styled, same: false },
'function.cjs': {
required: { function: 'plain' },
imported: {
default: { function: 'plain' },
'module.exports': { function: 'plain' },
extra: 1,
},
same: true,
},
'interop.cjs': {
required: { default: 'main', named: 'named' },
imported: {
default: 'main',
'module.exports': { default: 'main', named: 'named' },
named: 'named',
},
same: false,
},
'cycle-a.cjs': commonJs({ early: 'early', seen: 'early' }),
'syntax.cjs': {
required: { kind: 'module syntax' },
imported: { kind: 'module syntax' },
same: false,
},
'node_modules/cjs-lib/index.js': commonJs({ ...styled, name: 'cjs-lib' }),
})
// Every module's class is in the stylesheet, with its color
const classes = Object.values(results).flatMap(({ required }) =>
typeof required === 'object' &&
required !== null &&
'cls' in required &&
typeof required.cls === 'string'
? [required.cls]
: [],
)
expect(classes).toHaveLength(colors.length)
classes.forEach((cls, index) =>
expect(css).toContain(`.${cls}{color:#${colors[index]}}`),
)
}, 60000)
})
Loading
Loading