Skip to content

Commit d8e8a7f

Browse files
committed
fix(rsc): inject AsyncLocalStorage global via transform
1 parent e622a6a commit d8e8a7f

File tree

1 file changed

+33
-18
lines changed

1 file changed

+33
-18
lines changed

packages/plugin-rsc/src/plugin.ts

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -948,25 +948,40 @@ import.meta.hot.on("rsc:update", () => {
948948
// make `AsyncLocalStorage` available globally for React request context on edge build (e.g. React.cache, ssr preload)
949949
// https://github.com/facebook/react/blob/f14d7f0d2597ea25da12bcf97772e8803f2a394c/packages/react-server/src/forks/ReactFlightServerConfig.dom-edge.js#L16-L19
950950
name: 'rsc:inject-async-local-storage',
951-
async configureServer() {
952-
const __viteRscAyncHooks = await import('node:async_hooks')
953-
;(globalThis as any).AsyncLocalStorage =
954-
__viteRscAyncHooks.AsyncLocalStorage
955-
},
956-
banner(chunk) {
957-
if (
958-
(this.environment.name === 'ssr' ||
959-
this.environment.name === 'rsc') &&
960-
this.environment.mode === 'build' &&
961-
chunk.isEntry
962-
) {
963-
return `\
964-
import * as __viteRscAyncHooks from "node:async_hooks";
965-
globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;
966-
`
967-
}
968-
return ''
951+
// async configureServer() {
952+
// const __viteRscAyncHooks = await import('node:async_hooks')
953+
// ;(globalThis as any).AsyncLocalStorage =
954+
// __viteRscAyncHooks.AsyncLocalStorage
955+
// },
956+
transform: {
957+
handler(code) {
958+
if (
959+
this.environment.name !== 'client' &&
960+
code.includes('new AsyncLocalStorage()') &&
961+
!code.includes('__viteRscAyncHooks')
962+
) {
963+
return (
964+
`import * as __viteRscAyncHooks from "node:async_hooks";` +
965+
`globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;` +
966+
code
967+
)
968+
}
969+
},
969970
},
971+
// banner(chunk) {
972+
// if (
973+
// (this.environment.name === 'ssr' ||
974+
// this.environment.name === 'rsc') &&
975+
// this.environment.mode === 'build' &&
976+
// chunk.isEntry
977+
// ) {
978+
// return `\
979+
// import * as __viteRscAyncHooks from "node:async_hooks";
980+
// globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;
981+
// `
982+
// }
983+
// return ''
984+
// },
970985
},
971986
...vitePluginRscMinimal(rscPluginOptions, manager),
972987
...vitePluginFindSourceMapURL(),

0 commit comments

Comments
 (0)