@@ -53,6 +53,8 @@ import { validateImportPlugin } from './plugins/validate-import'
5353import { vitePluginFindSourceMapURL } from './plugins/find-source-map-url'
5454import { parseCssVirtual , toCssVirtual , parseIdQuery } from './plugins/shared'
5555
56+ const isRolldownVite = 'rolldownVersion' in vite
57+
5658const BUILD_ASSETS_MANIFEST_NAME = '__vite_rsc_assets_manifest.js'
5759
5860type 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