Skip to content
Merged
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
2 changes: 1 addition & 1 deletion packages/plugin-rsc/src/plugins/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function cjsModuleRunnerPlugin(): Plugin[] {
}

const ast = await parseAstAsync(code)
const result = transformCjsToEsm(code, ast)
const result = transformCjsToEsm(code, ast, { id })
const output = result.output
return {
code: output.toString(),
Expand Down
25 changes: 18 additions & 7 deletions packages/plugin-rsc/src/transforms/cjs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import path from 'node:path'
describe(transformCjsToEsm, () => {
async function testTransform(input: string) {
const ast = await parseAstAsync(input)
const { output } = transformCjsToEsm(input, ast)
const { output } = transformCjsToEsm(input, ast, { id: '/test.js' })
if (!output.hasChanged()) {
return
}
Expand All @@ -22,7 +22,8 @@ describe(transformCjsToEsm, () => {
exports.ok = true;
`
expect(await testTransform(input)).toMatchInlineSnapshot(`
"let exports = {}; const module = { exports };
"let __filename = "/test.js"; let __dirname = "/";
let exports = {}; const module = { exports };
exports.ok = true;

;__vite_ssr_exportAll__(module.exports);
Expand All @@ -41,7 +42,8 @@ if (true) {
}
`
expect(await testTransform(input)).toMatchInlineSnapshot(`
"let exports = {}; const module = { exports };
"let __filename = "/test.js"; let __dirname = "/";
let exports = {}; const module = { exports };
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')));
Expand All @@ -65,7 +67,8 @@ if (true) {
})()
`
expect(await testTransform(input)).toMatchInlineSnapshot(`
"let exports = {}; const module = { exports };
"let __filename = "/test.js"; let __dirname = "/";
let exports = {}; const module = { exports };
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"));
Expand Down Expand Up @@ -95,7 +98,8 @@ function test() {
}
`
expect(await testTransform(input)).toMatchInlineSnapshot(`
"let exports = {}; const module = { exports };
"let __filename = "/test.js"; let __dirname = "/";
let exports = {}; const module = { exports };
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"));
Expand Down Expand Up @@ -125,7 +129,8 @@ function test() {
}
`
expect(await testTransform(input)).toMatchInlineSnapshot(`
"let exports = {}; const module = { exports };
"let __filename = "/test.js"; let __dirname = "/";
let exports = {}; const module = { exports };
{
const require = () => {};
require("test");
Expand All @@ -149,7 +154,7 @@ function test() {
async transform(code, id) {
if (id.endsWith('.cjs')) {
const ast = await parseAstAsync(code)
const { output } = transformCjsToEsm(code, ast)
const { output } = transformCjsToEsm(code, ast, { id })
return {
code: output.toString(),
map: output.generateMap({ hires: 'boundary' }),
Expand All @@ -165,6 +170,12 @@ function test() {
const mod = await runner.import('/entry.mjs')
expect(mod).toMatchInlineSnapshot(`
{
"cjsGlobals": {
"test": [
"string",
"string",
],
},
"depDefault": {
"a": "a",
"b": "b",
Expand Down
11 changes: 11 additions & 0 deletions packages/plugin-rsc/src/transforms/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type { Program, Node } from 'estree'
import MagicString from 'magic-string'
import { analyze } from 'periscopic'
import { walk } from 'estree-walker'
import { fileURLToPath, pathToFileURL } from 'node:url'
import path from 'node:path'

// TODO:
// replacing require("xxx") into import("xxx") affects Vite's resolution.
Expand All @@ -14,6 +16,7 @@ const CJS_INTEROP_HELPER = `function __cjs_interop__(m) { return m.__cjs_module_
export function transformCjsToEsm(
code: string,
ast: Program,
options: { id: string },
): { output: MagicString } {
const output = new MagicString(code)
const analyzed = analyze(ast)
Expand Down Expand Up @@ -85,6 +88,14 @@ export function transformCjsToEsm(
// https://nodejs.org/docs/v22.19.0/api/modules.html#exports-shortcut
output.prepend(`let exports = {}; const module = { exports };\n`)

// https://nodejs.org/docs/v22.19.0/api/modules.html#the-module-scope
// https://github.com/vitest-dev/vitest/blob/965cefc19722a6c899cd1d3decb3cc33e72af696/packages/vite-node/src/client.ts#L548-L554
const __filename = fileURLToPath(pathToFileURL(options.id).href)
const __dirname = path.dirname(__filename)
output.prepend(
`let __filename = ${JSON.stringify(__filename)}; let __dirname = ${JSON.stringify(__dirname)};\n`,
)

// TODO: can we use cjs-module-lexer to properly define named exports?
// for re-exports, we need to eagerly transform dependencies though.
// https://github.com/nodejs/node/blob/f3adc11e37b8bfaaa026ea85c1cf22e3a0e29ae9/lib/internal/modules/esm/translators.js#L382-L409
Expand Down
2 changes: 2 additions & 0 deletions packages/plugin-rsc/src/transforms/fixtures/cjs/entry.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import depPrimitive from './primitive.cjs'
import depExports from './exports.cjs'
import depFnRequire from './function-require.cjs'
import dualLib from './dual-lib.cjs'
import cjsGlobals from './globals.cjs'
export {
depDefault,
depNamespace,
Expand All @@ -13,4 +14,5 @@ export {
depExports,
depFnRequire,
dualLib,
cjsGlobals,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.test = [typeof __filename, typeof __dirname]
Loading