fix preact aliases

This commit is contained in:
Jeppe Reinhold 2024-03-21 14:05:25 +01:00
parent ca283ff191
commit 694540aa44
3 changed files with 26 additions and 4 deletions

View File

@ -1,4 +1,4 @@
import { dirname, join } from 'path';
import { dirname, join, isAbsolute } from 'path';
import rehypeSlug from 'rehype-slug';
import rehypeExternalLinks from 'rehype-external-links';
@ -147,8 +147,8 @@ export const viteFinal = async (config: any, options: Options) => {
resolve: {
alias: {
react,
// Vite doesn't respect export maps when resolving a path, so we need to do that manually here
'react-dom/server': `${reactDom}/server.browser.js`,
// Vite doesn't respect export maps when resolving an absolute path, so we need to do that manually here
...(isAbsolute(reactDom) && { 'react-dom/server': `${reactDom}/server.browser.js` }),
'react-dom': reactDom,
'@mdx-js/react': mdx,
/**

View File

@ -1,5 +1,5 @@
import type { Options } from '@storybook/types';
import { join, dirname } from 'path';
import { join, dirname, isAbsolute } from 'path';
import { readFile } from 'fs/promises';
/**
@ -17,6 +17,12 @@ const getIsReactVersion18 = async (options: Options) => {
const resolvedReact = await options.presets.apply<{ reactDom?: string }>('resolvedReact', {});
const reactDom = resolvedReact.reactDom || dirname(require.resolve('react-dom/package.json'));
if (!isAbsolute(reactDom)) {
// if react-dom is not resolved to a file we can't be sure if the version in package.json is correct or even if package.json exists
// this happens when react-dom is resolved to 'preact/compat' for example
return false;
}
const { version } = JSON.parse(await readFile(join(reactDom, 'package.json'), 'utf-8'));
return version.startsWith('18') || version.startsWith('0.0.0');
};

View File

@ -13,3 +13,19 @@ export const previewAnnotations: PresetProperty<'previewAnnotations'> = async (
.concat([join(__dirname, 'entry-preview.mjs')])
.concat(docsEnabled ? [join(__dirname, 'entry-preview-docs.mjs')] : []);
};
/**
* Alias react and react-dom to preact/compat similar to the preact vite preset
* https://github.com/preactjs/preset-vite/blob/main/src/index.ts#L238-L239
*/
export const resolvedReact = async (existing: any) => {
try {
return {
...existing,
react: 'preact/compat',
reactDom: 'preact/compat',
};
} catch (e) {
return existing;
}
};