Try a different approach to importing different React versions

This commit is contained in:
delucis 2022-03-30 11:56:33 +02:00
parent 2ea2a31db7
commit a84ff5ee63
No known key found for this signature in database
GPG key ID: 52DB15DC07051619
2 changed files with 11 additions and 9 deletions

View file

@ -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);
};

View file

@ -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'],