@@ -373,13 +373,15 @@ function createFinalPlugins(
373373}
374374
375375/**
376- * use @vitejs/plugin-react to handle the output of @mdx-js/rollup
376+ * use @vitejs/plugin-react to transform the output of @mdx-js/rollup,
377+ * adding react-refresh hmr ability to .md and .mdx files
377378 * workaround this issue: https://github.com/vitejs/vite-plugin-react/issues/38
378379 */
379380function createMdxTransformPlugin ( ) : Plugin {
380381 let vitePluginReactTrasnform : Plugin [ 'transform' ] | undefined
382+ const PLUGIN_NAME = 'vite-pages:mdx-fast-refresh'
381383 return {
382- name : 'vite-pages:mdx-fast-refresh' ,
384+ name : PLUGIN_NAME ,
383385 apply : 'serve' ,
384386 configResolved : ( { plugins } ) => {
385387 // find this plugin to call it's transform function:
@@ -396,13 +398,33 @@ function createMdxTransformPlugin(): Plugin {
396398 `Can't find an instance of @vitejs/plugin-react or @vitejs/plugin-react-swc. You should apply either of these plugins to make mdx work.`
397399 )
398400 }
401+ const reactSwcPluginIndex = plugins . findIndex (
402+ ( p ) => p . name === 'vite:react-swc' && typeof p . transform === 'function'
403+ )
404+ const thisPluginIndex = plugins . findIndex ( ( p ) => p . name === PLUGIN_NAME )
405+ if (
406+ reactSwcPluginIndex !== - 1 &&
407+ thisPluginIndex !== - 1 &&
408+ reactSwcPluginIndex > thisPluginIndex
409+ ) {
410+ throw new Error (
411+ '[vite-plugin-react-pages]: @vitejs/plugin-react-swc should be placed before this plugin'
412+ )
413+ }
399414 } ,
400415 transform : ( code , id , options ) => {
401416 const [ filepath , ...qs ] = id . split ( '?' )
402417 if (
403418 filepath . match ( / \. m d x ? $ / ) &&
404419 ! id . startsWith ( OUTLINE_INFO_MODULE_ID_PREFIX )
405420 ) {
421+ const refreshContentRE = / \$ R e f r e s h (?: R e g | S i g ) \$ \( /
422+ if ( code . includes ( '/@react-refresh' ) && refreshContentRE . test ( code ) ) {
423+ // the mdx output has already been transformed by @vitejs /plugin-react-swc
424+ // https://github.com/vitejs/vite-plugin-react-swc/blob/95e991914322e7b011d1c8d18d501b9eee21adaa/src/index.ts#L199C3-L199C3
425+ // don't transform it again
426+ return
427+ }
406428 // turn file path like `/path/to/md-file$.md` into `/path/to/md-file$.jsx`
407429 // make vite-plugin-react transform "the output of @mdx-js/rollup" like a jsx file
408430 // https://github.com/vitejs/vite-plugin-react/blob/caa9b5330092c70288fcb94ceb96ca42438df2a2/packages/plugin-react/src/index.ts#L170
0 commit comments