Skip to content

Commit a711f1c

Browse files
authored
fix(ssr): convert external require against built-in modules to import for ssr.target=webworker (#23759)
1 parent 0672bf8 commit a711f1c

10 files changed

Lines changed: 232 additions & 207 deletions

File tree

‎packages/vite/src/node/build.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import type {
2424
WatcherOptions,
2525
} from 'rolldown'
2626
import { viteLoadFallbackPlugin as nativeLoadFallbackPlugin } from 'rolldown/experimental'
27-
import { esmExternalRequirePlugin } from 'rolldown/plugins'
2827
import type { RollupCommonJSOptions } from '#dep-types/commonjs'
2928
import type { RollupDynamicImportVarsOptions } from '#dep-types/dynamicImportVars'
3029
import type { EsbuildTarget } from '#types/internal/esbuildOptions'
@@ -710,12 +709,6 @@ export function resolveRolldownOptions(
710709
environment.name === 'ssr' &&
711710
environment.getTopLevelConfig().ssr?.target === 'webworker'
712711

713-
// For webworker SSR with platform: 'browser', external CJS require() calls
714-
// need to be converted to ESM imports since createRequire is not available.
715-
if (isSsrTargetWebworkerEnvironment) {
716-
plugins.push(esmExternalRequirePlugin())
717-
}
718-
719712
const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => {
720713
// @ts-expect-error See https://github.com/vitejs/vite/issues/5812#issuecomment-984345618
721714
if (output.output) {

‎packages/vite/src/node/plugins/resolve.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,10 @@ export function oxcResolvePlugin(
280280
},
281281
environmentConsumer: partialEnv.config.consumer,
282282
environmentName: partialEnv.name,
283+
convertExternalRequire:
284+
options.isBuild &&
285+
partialEnv.name === 'ssr' &&
286+
partialEnv.config.ssr.target === 'webworker',
283287
builtins: partialEnv.config.resolve.builtins,
284288
external: options.external,
285289
noExternal: noExternal,

‎playground/ssr-webworker/__tests__/serve.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33

44
import path from 'node:path'
55
import kill from 'kill-port'
6-
import { ports, rootDir } from '~utils'
6+
import { createInMemoryLogger, ports, rootDir } from '~utils'
77

88
export const port = ports['ssr-webworker']
9+
export const serverLogs: string[] = []
910

1011
export async function serve(): Promise<{ close(): Promise<void> }> {
1112
await kill(port)
@@ -17,7 +18,7 @@ export async function serve(): Promise<{ close(): Promise<void> }> {
1718
// worker build
1819
await build({
1920
root: rootDir,
20-
logLevel: 'silent',
21+
customLogger: createInMemoryLogger(serverLogs),
2122
build: {
2223
target: 'esnext',
2324
ssr: 'src/entry-worker.jsx',

‎playground/ssr-webworker/__tests__/ssr-webworker.spec.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import nodePath from 'node:path'
2+
import type { RolldownOutput, OutputChunk } from 'rolldown'
3+
import { build } from 'vite'
14
import { expect, test } from 'vitest'
2-
import { findAssetFile, isBuild, page } from '~utils'
3-
import { port } from './serve'
5+
import { findAssetFile, isBuild, page, rootDir } from '~utils'
6+
import { port, serverLogs } from './serve'
47

58
const url = `http://localhost:${port}`
69

@@ -30,12 +33,51 @@ test('supports nodejs_compat', async () => {
3033
)
3134
})
3235

36+
test('supports requiring an external node builtin from CommonJS', async () => {
37+
await page.goto(url)
38+
expect(await page.textContent('.cjs-node-builtin')).toMatch(
39+
'[success] cjs node builtin require',
40+
)
41+
})
42+
43+
test('warns when automatically externalizing a node builtin', () => {
44+
const logs = serverLogs.join('\n')
45+
expect(logs).toContain(
46+
'Automatically externalized node built-in module "node:util"',
47+
)
48+
})
49+
3350
test.runIf(isBuild)('build output does not contain createRequire', async () => {
3451
const workerContent = findAssetFile(/entry-worker/, 'worker', '')
3552
expect(workerContent).toBeDefined()
3653
expect(workerContent).not.toContain('createRequire')
3754
})
3855

56+
test.runIf(isBuild)(
57+
'converts a CommonJS require for an installed Node builtin package to an import',
58+
async () => {
59+
const output = (await build({
60+
configFile: false,
61+
root: nodePath.join(rootDir, 'cjs-node-builtin'),
62+
logLevel: 'silent',
63+
ssr: {
64+
target: 'webworker',
65+
external: ['util'],
66+
},
67+
build: {
68+
ssr: 'installed-node-builtin.cjs',
69+
write: false,
70+
},
71+
})) as RolldownOutput
72+
const entry = output.output.find(
73+
(file): file is OutputChunk => file.type === 'chunk' && file.isEntry,
74+
)
75+
76+
expect(entry?.code).toContain('from "util"')
77+
expect(entry?.code).not.toContain('__require("util")')
78+
},
79+
)
80+
3981
test.runIf(isBuild)('codeSplitting: false', () => {
4082
const dynamicJsContent = findAssetFile(/dynamic-[-\w]+\.js/, 'worker')
4183
expect(dynamicJsContent).toBeUndefined()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const util = require('node:util')
2+
3+
module.exports.format = () =>
4+
util.format('[success] %s', 'cjs node builtin require')
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// The bare specifier exercises resolution when the npm package is installed.
2+
// eslint-disable-next-line n/prefer-node-protocol
3+
module.exports = require('util')
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"name": "@vitejs/test-cjs-node-builtin",
3+
"private": true,
4+
"version": "0.0.0",
5+
"exports": "./index.cjs",
6+
"dependencies": {
7+
"util": "0.12.5"
8+
}
9+
}

‎playground/ssr-webworker/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"dependencies": {
1111
"react": "^19.3.1",
1212
"@vitejs/test-browser-exports": "file:./browser-exports",
13+
"@vitejs/test-cjs-node-builtin": "file:./cjs-node-builtin",
1314
"@vitejs/test-worker-exports": "file:./worker-exports"
1415
},
1516
"devDependencies": {

‎playground/ssr-webworker/src/entry-worker.jsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { equal } from 'node:assert'
22
import browserExportsMessage from '@vitejs/test-browser-exports'
3+
import { format as cjsBuiltinRequire } from '@vitejs/test-cjs-node-builtin'
34
import { msg as linkedMsg } from '@vitejs/test-resolve-linked'
45
import workerExportsMessage from '@vitejs/test-worker-exports'
56
import React from 'react'
@@ -20,6 +21,7 @@ addEventListener('fetch', function (event) {
2021
<p class="browser-exports">${browserExportsMessage}</p>
2122
<p class="worker-exports">${workerExportsMessage}</p>
2223
<p class="nodejs-compat">${equal('a', 'a') || '[success] nodejs compat'}</p>
24+
<p class="cjs-node-builtin">${cjsBuiltinRequire()}</p>
2325
`,
2426
{
2527
headers: {

0 commit comments

Comments
 (0)