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
32 changes: 31 additions & 1 deletion packages/plugin-rsc/src/transforms/cjs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ if (true) {
`
expect(await testTransform(input)).toMatchInlineSnapshot(`
"const exports = {}; const module = { exports };
const __cjs_to_esm_hoist_1 = await import("react-dom");
const __cjs_to_esm_hoist_0 = await import("react");
const __cjs_to_esm_hoist_1 = 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 @@ -68,6 +68,36 @@ if (true) {
`)
})

it('edge cases', async () => {
const input = `\
const x1 = require("te" + "st");
const x2 = require("test")().test;
console.log(require("test"))

function test() {
const y1 = require("te" + "st");
const y2 = require("test")().test;
consoe.log(require("test"))
}
`
expect(await testTransform(input)).toMatchInlineSnapshot(`
"const exports = {}; const module = { exports };
const __cjs_to_esm_hoist_0 = await import("te" + "st");
const __cjs_to_esm_hoist_1 = await import("test");
const __cjs_to_esm_hoist_2 = await import("test");
const x1 = (await import("te" + "st"));
const x2 = (await import("test"))().test;
console.log((await import("test")))

function test() {
const y1 = __cjs_to_esm_hoist_0;
const y2 = __cjs_to_esm_hoist_1().test;
consoe.log(__cjs_to_esm_hoist_2)
}
"
`)
})

it('local require', async () => {
const input = `\
{
Expand Down
8 changes: 6 additions & 2 deletions packages/plugin-rsc/src/transforms/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export function transformCjsToEsm(
const output = new MagicString(code)
const analyzed = analyze(ast)

let parentNodes: Node[] = []
const parentNodes: Node[] = []
const hoistedCodes: string[] = []
let hoistIndex = 0
walk(ast, {
enter(node) {
Expand Down Expand Up @@ -49,7 +50,7 @@ export function transformCjsToEsm(
node.arguments[0]!.start,
node.arguments[0]!.end,
)
output.prepend(`const ${hoisted} = await import(${importee});\n`)
hoistedCodes.push(`const ${hoisted} = await import(${importee});\n`)
output.update(node.start, node.end, hoisted)
hoistIndex++
}
Expand All @@ -59,6 +60,9 @@ export function transformCjsToEsm(
parentNodes.pop()!
},
})
for (const hoisted of hoistedCodes.reverse()) {
output.prepend(hoisted)
}
output.prepend(`const exports = {}; const module = { exports };\n`)
return { output }
}
Loading