Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
23 changes: 13 additions & 10 deletions packages/plugin-rsc/src/transforms/cjs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,13 @@
module.exports = require('./cjs/use-sync-external-store.development.js');
}
`
expect(await testTransform(input)).toMatchInlineSnapshot(`

Check failure on line 39 in packages/plugin-rsc/src/transforms/cjs.test.ts

View workflow job for this annotation

GitHub Actions / copilot

src/transforms/cjs.test.ts > transformCjsToEsm > top-level re-export

Error: Snapshot `transformCjsToEsm > top-level re-export 1` mismatched - Expected + Received @@ -1,7 +1,7 @@ "let exports = {}; const module = { exports }; - function __cjs_interop__(m) { return m && m.__esModule ? m.default : (m.default !== undefined ? m.default : m); } + function __cjs_interop__(m) { return m.__cjs_module_runner_transform ? m.default : m; } if (true) { module.exports = (__cjs_interop__(await import('./cjs/use-sync-external-store.production.js'))); } else { module.exports = (__cjs_interop__(await import('./cjs/use-sync-external-store.development.js'))); } ❯ src/transforms/cjs.test.ts:39:40
"let exports = {}; const module = { exports };
function __cjs_interop__(m) { return m && m.__esModule ? m.default : (m.default !== undefined ? m.default : m); }
if (true) {
module.exports = ((await import('./cjs/use-sync-external-store.production.js')).default);
module.exports = (__cjs_interop__(await import('./cjs/use-sync-external-store.production.js')));
} else {
module.exports = ((await import('./cjs/use-sync-external-store.development.js')).default);
module.exports = (__cjs_interop__(await import('./cjs/use-sync-external-store.development.js')));
}
"
`)
Expand All @@ -55,10 +56,11 @@
exports.useSyncExternalStoreWithSelector = function () {}
})()
`
expect(await testTransform(input)).toMatchInlineSnapshot(`

Check failure on line 59 in packages/plugin-rsc/src/transforms/cjs.test.ts

View workflow job for this annotation

GitHub Actions / copilot

src/transforms/cjs.test.ts > transformCjsToEsm > non top-level re-export

Error: Snapshot `transformCjsToEsm > non top-level re-export 1` mismatched - Expected + Received @@ -1,7 +1,7 @@ "let exports = {}; const module = { exports }; - function __cjs_interop__(m) { return m && m.__esModule ? m.default : (m.default !== undefined ? m.default : m); } + function __cjs_interop__(m) { return m.__cjs_module_runner_transform ? m.default : m; } const __cjs_to_esm_hoist_0 = __cjs_interop__(await import("react")); const __cjs_to_esm_hoist_1 = __cjs_interop__(await import("react-dom")); "production" !== process.env.NODE_ENV && (function() { var React = __cjs_to_esm_hoist_0; var ReactDOM = __cjs_to_esm_hoist_1; ❯ src/transforms/cjs.test.ts:59:40
"let exports = {}; const module = { exports };
const __cjs_to_esm_hoist_0 = (await import("react")).default;
const __cjs_to_esm_hoist_1 = (await import("react-dom")).default;
function __cjs_interop__(m) { return m && m.__esModule ? m.default : (m.default !== undefined ? m.default : m); }
const __cjs_to_esm_hoist_0 = __cjs_interop__(await import("react"));
const __cjs_to_esm_hoist_1 = __cjs_interop__(await import("react-dom"));
"production" !== process.env.NODE_ENV && (function() {
var React = __cjs_to_esm_hoist_0;
var ReactDOM = __cjs_to_esm_hoist_1;
Expand All @@ -80,14 +82,15 @@
consoe.log(require("test"))
}
`
expect(await testTransform(input)).toMatchInlineSnapshot(`

Check failure on line 85 in packages/plugin-rsc/src/transforms/cjs.test.ts

View workflow job for this annotation

GitHub Actions / copilot

src/transforms/cjs.test.ts > transformCjsToEsm > edge cases

Error: Snapshot `transformCjsToEsm > edge cases 1` mismatched - Expected + Received @@ -1,7 +1,7 @@ "let exports = {}; const module = { exports }; - function __cjs_interop__(m) { return m && m.__esModule ? m.default : (m.default !== undefined ? m.default : m); } + function __cjs_interop__(m) { return m.__cjs_module_runner_transform ? m.default : m; } const __cjs_to_esm_hoist_0 = __cjs_interop__(await import("te" + "st")); const __cjs_to_esm_hoist_1 = __cjs_interop__(await import("test")); const __cjs_to_esm_hoist_2 = __cjs_interop__(await import("test")); const x1 = (__cjs_interop__(await import("te" + "st"))); const x2 = (__cjs_interop__(await import("test")))().test; ❯ src/transforms/cjs.test.ts:85:40
"let exports = {}; const module = { exports };
const __cjs_to_esm_hoist_0 = (await import("te" + "st")).default;
const __cjs_to_esm_hoist_1 = (await import("test")).default;
const __cjs_to_esm_hoist_2 = (await import("test")).default;
const x1 = ((await import("te" + "st")).default);
const x2 = ((await import("test")).default)().test;
console.log(((await import("test")).default))
function __cjs_interop__(m) { return m && m.__esModule ? m.default : (m.default !== undefined ? m.default : m); }
const __cjs_to_esm_hoist_0 = __cjs_interop__(await import("te" + "st"));
const __cjs_to_esm_hoist_1 = __cjs_interop__(await import("test"));
const __cjs_to_esm_hoist_2 = __cjs_interop__(await import("test"));
const x1 = (__cjs_interop__(await import("te" + "st")));
const x2 = (__cjs_interop__(await import("test")))().test;
console.log((__cjs_interop__(await import("test"))))

function test() {
const y1 = __cjs_to_esm_hoist_0;
Expand Down Expand Up @@ -143,7 +146,7 @@
const runner = createServerModuleRunner(server.environments.ssr, {
hmr: false,
})
const mod = await runner.import('/entry.mjs')

Check failure on line 149 in packages/plugin-rsc/src/transforms/cjs.test.ts

View workflow job for this annotation

GitHub Actions / copilot

src/transforms/cjs.test.ts > transformCjsToEsm > e2e

TypeError: lib is not a function ❯ eval src/transforms/fixtures/cjs/function-require.cjs:7:17 ❯ ESModulesEvaluator.runInlinedModule ../../node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/module-runner.js:906:3 ❯ ModuleRunner.directRequest ../../node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/module-runner.js:1113:59 ❯ ModuleRunner.cachedRequest ../../node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/module-runner.js:1031:73 ❯ eval src/transforms/fixtures/cjs/entry.mjs:14:31 ❯ ESModulesEvaluator.runInlinedModule ../../node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/module-runner.js:906:3 ❯ ModuleRunner.directRequest ../../node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/module-runner.js:1113:59 ❯ ModuleRunner.cachedRequest ../../node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/module-runner.js:1031:73 ❯ ModuleRunner.import ../../node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/module-runner.js:992:10 ❯ src/transforms/cjs.test.ts:149:17
expect(mod).toMatchInlineSnapshot(`
{
"depDefault": {
Expand Down
27 changes: 23 additions & 4 deletions packages/plugin-rsc/src/transforms/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import MagicString from 'magic-string'
import { analyze } from 'periscopic'
import { walk } from 'estree-walker'

// Runtime helper to handle CJS/ESM interop when transforming require() to import()
// This is needed because when CJS code does require("pkg"), it expects:
// - For CJS modules: the module.exports value directly
// - For ESM modules: Node.js actually returns the namespace object
// Since we're transforming to dynamic import(), we need to handle both cases
const CJS_INTEROP_HELPER = `function __cjs_interop__(m) { return m && m.__esModule ? m.default : (m.default !== undefined ? m.default : m); }`

export function transformCjsToEsm(
code: string,
ast: Program,
Expand All @@ -13,6 +20,8 @@ export function transformCjsToEsm(
const parentNodes: Node[] = []
const hoistedCodes: string[] = []
let hoistIndex = 0
let needsInteropHelper = false

walk(ast, {
enter(node) {
parentNodes.push(node)
Expand All @@ -38,11 +47,17 @@ export function transformCjsToEsm(
}
}

needsInteropHelper = true

if (isTopLevel) {
// top-level scope `require` to dynamic import
// top-level scope `require` to dynamic import with interop
// (this allows handling react development/production re-export within top-level if branch)
output.update(node.start, node.callee.end, '((await import')
output.appendRight(node.end, ').default)')
output.update(
node.start,
node.callee.end,
'(__cjs_interop__(await import',
)
output.appendRight(node.end, '))')
} else {
// hoist non top-level `require` to top-level
const hoisted = `__cjs_to_esm_hoist_${hoistIndex}`
Expand All @@ -51,7 +66,7 @@ export function transformCjsToEsm(
node.arguments[0]!.end,
)
hoistedCodes.push(
`const ${hoisted} = (await import(${importee})).default;\n`,
`const ${hoisted} = __cjs_interop__(await import(${importee}));\n`,
)
output.update(node.start, node.end, hoisted)
hoistIndex++
Expand All @@ -65,6 +80,10 @@ export function transformCjsToEsm(
for (const hoisted of hoistedCodes.reverse()) {
output.prepend(hoisted)
}
// Prepend interop helper if needed
if (needsInteropHelper) {
output.prepend(`${CJS_INTEROP_HELPER}\n`)
}
// https://nodejs.org/docs/v22.19.0/api/modules.html#exports-shortcut
output.prepend(`let exports = {}; const module = { exports };\n`)
return { output }
Expand Down