@@ -373,13 +373,15 @@ function createFinalPlugins(
373
373
}
374
374
375
375
/**
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
377
378
* workaround this issue: https://github.com/vitejs/vite-plugin-react/issues/38
378
379
*/
379
380
function createMdxTransformPlugin ( ) : Plugin {
380
381
let vitePluginReactTrasnform : Plugin [ 'transform' ] | undefined
382
+ const PLUGIN_NAME = 'vite-pages:mdx-fast-refresh'
381
383
return {
382
- name : 'vite-pages:mdx-fast-refresh' ,
384
+ name : PLUGIN_NAME ,
383
385
apply : 'serve' ,
384
386
configResolved : ( { plugins } ) => {
385
387
// find this plugin to call it's transform function:
@@ -396,13 +398,33 @@ function createMdxTransformPlugin(): Plugin {
396
398
`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.`
397
399
)
398
400
}
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
+ }
399
414
} ,
400
415
transform : ( code , id , options ) => {
401
416
const [ filepath , ...qs ] = id . split ( '?' )
402
417
if (
403
418
filepath . match ( / \. m d x ? $ / ) &&
404
419
! id . startsWith ( OUTLINE_INFO_MODULE_ID_PREFIX )
405
420
) {
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
+ }
406
428
// turn file path like `/path/to/md-file$.md` into `/path/to/md-file$.jsx`
407
429
// make vite-plugin-react transform "the output of @mdx-js/rollup" like a jsx file
408
430
// https://github.com/vitejs/vite-plugin-react/blob/caa9b5330092c70288fcb94ceb96ca42438df2a2/packages/plugin-react/src/index.ts#L170
0 commit comments