diff --git a/code/lib/builder-vite/src/plugins/mdx-plugin.ts b/code/lib/builder-vite/src/plugins/mdx-plugin.ts index 2527921004f..6bd26d01534 100644 --- a/code/lib/builder-vite/src/plugins/mdx-plugin.ts +++ b/code/lib/builder-vite/src/plugins/mdx-plugin.ts @@ -1,6 +1,7 @@ import type { Options } from '@storybook/types'; import type { Plugin } from 'vite'; import { createFilter } from 'vite'; +import reactVite from '@vitejs/plugin-react'; const isStorybookMdx = (id: string) => id.endsWith('stories.mdx') || id.endsWith('story.mdx'); @@ -11,6 +12,11 @@ function injectRenderer(code: string) { `; } +// HACK: find a better way to do this, ideally avoiding @vitejs/plugin-react entirely. +// We're just using it to run the mdx with jsx through babel +// @ts-expect-error we know these have names, and what the shape will be +const viteBabel: Plugin | undefined = reactVite().find((p) => p.name === 'vite:react-babel'); + /** * Storybook uses two different loaders when dealing with MDX: * @@ -20,28 +26,12 @@ function injectRenderer(code: string) { * @see https://github.com/storybookjs/storybook/blob/next/addons/docs/docs/recipes.md#csf-stories-with-arbitrary-mdx */ export function mdxPlugin(options: Options): Plugin { - let reactRefresh: Plugin | undefined; const include = /\.mdx?$/; const filter = createFilter(include); return { name: 'storybook:mdx-plugin', enforce: 'pre', - configResolved({ plugins }) { - // @vitejs/plugin-react-refresh has been upgraded to @vitejs/plugin-react, - // and the name of the plugin performing `transform` has been changed from 'react-refresh' to 'vite:react-babel', - // to be compatible, we need to look for both plugin name. - // We should also look for the other plugins names exported from @vitejs/plugin-react in case there are some internal refactors. - const reactRefreshPlugins = plugins.filter( - (p) => - p.name === 'react-refresh' || - p.name === 'vite:react-babel' || - p.name === 'vite:react-refresh' || - p.name === 'vite:react-jsx' - ); - reactRefresh = reactRefreshPlugins.find((p) => p.transform); - }, - async transform(src, id, transformOptions) { if (!filter(id)) return undefined; @@ -63,7 +53,7 @@ export function mdxPlugin(options: Options): Plugin { const modifiedCode = injectRenderer(mdxCode); // Hooks in recent rollup versions can be functions or objects, and though react hasn't changed, the typescript defs have - const rTransform = reactRefresh?.transform; + const rTransform = viteBabel?.transform; const transform = rTransform && 'handler' in rTransform ? rTransform.handler : rTransform; // It's safe to disable this, because we know it'll be there, since we added it ourselves.