Skip to content

Commit 2f255ad

Browse files
authored
fix(rsc): inject AsyncLocalStorage global via transform (#785)
1 parent e3bf733 commit 2f255ad

File tree

1 file changed

+22
-19
lines changed

1 file changed

+22
-19
lines changed

packages/plugin-rsc/src/plugin.ts

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ import { validateImportPlugin } from './plugins/validate-import'
5353
import { vitePluginFindSourceMapURL } from './plugins/find-source-map-url'
5454
import { parseCssVirtual, toCssVirtual, parseIdQuery } from './plugins/shared'
5555

56+
const isRolldownVite = 'rolldownVersion' in vite
57+
5658
const BUILD_ASSETS_MANIFEST_NAME = '__vite_rsc_assets_manifest.js'
5759

5860
type ClientReferenceMeta = {
@@ -946,27 +948,28 @@ import.meta.hot.on("rsc:update", () => {
946948
},
947949
),
948950
{
949-
// make `AsyncLocalStorage` available globally for React request context on edge build (e.g. React.cache, ssr preload)
951+
// make `AsyncLocalStorage` available globally for React edge build (required for React.cache, ssr preload, etc.)
950952
// https://github.com/facebook/react/blob/f14d7f0d2597ea25da12bcf97772e8803f2a394c/packages/react-server/src/forks/ReactFlightServerConfig.dom-edge.js#L16-L19
951953
name: 'rsc:inject-async-local-storage',
952-
async configureServer() {
953-
const __viteRscAyncHooks = await import('node:async_hooks')
954-
;(globalThis as any).AsyncLocalStorage =
955-
__viteRscAyncHooks.AsyncLocalStorage
956-
},
957-
banner(chunk) {
958-
if (
959-
(this.environment.name === 'ssr' ||
960-
this.environment.name === 'rsc') &&
961-
this.environment.mode === 'build' &&
962-
chunk.isEntry
963-
) {
964-
return `\
965-
import * as __viteRscAyncHooks from "node:async_hooks";
966-
globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;
967-
`
968-
}
969-
return ''
954+
transform: {
955+
handler(code) {
956+
if (
957+
(this.environment.name === 'ssr' ||
958+
this.environment.name === 'rsc') &&
959+
code.includes('typeof AsyncLocalStorage') &&
960+
code.includes('new AsyncLocalStorage()') &&
961+
!code.includes('__viteRscAyncHooks')
962+
) {
963+
// for build, we cannot use `import` as it confuses rollup commonjs plugin.
964+
return (
965+
(this.environment.mode === 'build' && !isRolldownVite
966+
? `const __viteRscAyncHooks = require("node:async_hooks");`
967+
: `import * as __viteRscAyncHooks from "node:async_hooks";`) +
968+
`globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;` +
969+
code
970+
)
971+
}
972+
},
970973
},
971974
},
972975
...vitePluginRscMinimal(rscPluginOptions, manager),

0 commit comments

Comments
 (0)