Skip to content

Commit

Permalink
Merge pull request #20121 from storybookjs/fix/vite-docs-mdx
Browse files Browse the repository at this point in the history
Vite/MDX: Fix mdx compiler for vite
  • Loading branch information
ndelangen authored Dec 7, 2022
2 parents b43cd8a + e1a3a82 commit 4880bfa
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
20 changes: 16 additions & 4 deletions code/lib/builder-vite/src/plugins/mdx-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Options } from '@storybook/types';
import type { Plugin } from 'vite';
import { createFilter } from 'vite';

Expand All @@ -18,7 +19,7 @@ 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(): Plugin {
export function mdxPlugin(options: Options): Plugin {
let reactRefresh: Plugin | undefined;
const include = /\.mdx?$/;
const filter = createFilter(include);
Expand All @@ -41,12 +42,23 @@ export function mdxPlugin(): Plugin {
reactRefresh = reactRefreshPlugins.find((p) => p.transform);
},

async transform(src, id, options) {
async transform(src, id, transformOptions) {
if (!filter(id)) return undefined;

const { compile } = await import('@storybook/mdx2-csf');

const mdxCode = String(await compile(src, { skipCsf: !isStorybookMdx(id) }));
const mdxLoaderOptions = await options.presets.apply('mdxLoaderOptions', {
mdxCompileOptions: {
providerImportSource: '@storybook/addon-docs/mdx-react-shim',
},
});

const mdxCode = String(
await compile(src, {
skipCsf: !isStorybookMdx(id),
...mdxLoaderOptions,
})
);

const modifiedCode = injectRenderer(mdxCode);

Expand All @@ -56,7 +68,7 @@ export function mdxPlugin(): Plugin {

// It's safe to disable this, because we know it'll be there, since we added it ourselves.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const result = await transform!.call(this, modifiedCode, `${id}.jsx`, options);
const result = await transform!.call(this, modifiedCode, `${id}.jsx`, transformOptions);

if (!result) return modifiedCode;

Expand Down
2 changes: 1 addition & 1 deletion code/lib/builder-vite/src/vite-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export async function pluginConfig(options: ExtendedOptions) {
const plugins = [
codeGeneratorPlugin(options),
// sourceLoaderPlugin(options),
mdxPlugin(),
mdxPlugin(options),
injectExportOrderPlugin,
stripStoryHMRBoundary(),
{
Expand Down

0 comments on commit 4880bfa

Please sign in to comment.