diff --git a/packages/integrations/react/client.js b/packages/integrations/react/client.js index 0cea3492a..7bd0ad8db 100644 --- a/packages/integrations/react/client.js +++ b/packages/integrations/react/client.js @@ -1,15 +1,13 @@ import { createElement } from 'react'; -import { version } from 'react-dom/package.json'; import StaticHtml from './static-html.js'; -const usingReact18 = version.startsWith('18.'); +const usingReact18 = process.env.REACT_HYDRATION_ENTRYPOINT === 'react-dom/client'; // Import the correct hydration method based on the version of React. -const hydrateFn = ( - async () => usingReact18 - ? (await import('react-dom/client.js')).hydrateRoot - : (await import('react-dom')).hydrate -)(); +const hydrateFn = (async () => { + const mod = await import(process.env.REACT_HYDRATION_ENTRYPOINT); + return mod[usingReact18 ? 'hydrateRoot' : 'hydrate']; +})(); export default (element) => async (Component, props, children) => { const args = [ @@ -20,9 +18,9 @@ export default (element) => async (Component, props, children) => { ), element, ]; - + // `hydrateRoot` expects [container, component] instead of [component, container]. if (usingReact18) args.reverse(); - + return (await hydrateFn)(...args); }; diff --git a/packages/integrations/react/src/index.ts b/packages/integrations/react/src/index.ts index c5475e29e..ef8b97f51 100644 --- a/packages/integrations/react/src/index.ts +++ b/packages/integrations/react/src/index.ts @@ -1,4 +1,5 @@ import { AstroIntegration } from 'astro'; +import { version as ReactVersion } from 'react-dom/package.json'; function getRenderer() { return { @@ -28,6 +29,9 @@ function getRenderer() { function getViteConfiguration() { return { + define: { + 'process.env.REACT_HYDRATION_ENTRYPOINT': ReactVersion.startsWith('18.') ? 'react-dom/client' : 'react-dom', + }, optimizeDeps: { include: ['@astrojs/react/client.js', 'react', 'react/jsx-runtime', 'react/jsx-dev-runtime', 'react-dom'], exclude: ['@astrojs/react/server.js'],