Compile Markdown to React component.
- 📚 Use Markdown as React components.
- 💚 Use React components in Markdown.
npm i -D vite-plugin-markdown-reactAdd it to vite.config.js
// vite.config.jsimportreactfrom'@vitejs/plugin-react'importMarkdownfrom'vite-plugin-markdown-react'/** @type {import 'vite'.UserConfig} */exportdefaultdefineConfig({plugins: [react(),Markdown()],})And import it as a normal React component
importHelloWorldfrom'./README'exportdefaultfunctionReactComponent(){return<HelloWorld/>}Work with unplugin-auto-import
// vite.config.jsimportreactfrom'@vitejs/plugin-react'importMarkdownfrom'vite-plugin-markdown-react'importAutoImportfrom'unplugin-auto-import/vite'/** @type {import 'vite'.UserConfig} */exportdefaultdefineConfig({plugins: [react(),Markdown(),AutoImport({include: [/\.[tj]sx?$/,/\.md$/],imports: [imports],dts: true,}),],})// importsconstimports=awaitgetAutoImports(['src/components/**/*.tsx']);typeImports=Record<string,['default',string][]>;exportconstgetAutoImports=async(pattern: Pattern[]): Promise<Imports>=>{
const files=awaitfg(pattern,{absolute: false});constmap=newMap<string,['default',string][]>([]);for(constfileoffiles){constpathWithoutExt=file.replace(/\.(tsx|jsx)$/,'');constimportPath=`@/${pathWithoutExt.replace(/^src\//,'')}`;constfileName=pathWithoutExt.split('/').pop();if(fileName){map.set(importPath,[['default',fileName]]);}}returnObject.fromEntries(map);};Components under ./src/components can be directly used in markdown components, and markdown components can also be put under ./src/components to be auto imported.
You can use frontmatter in .md
---name: My Cool App---# Hello World
This is {frontmatter.name}Will be rendered as
<h1>Hello World</h1><p>This is My React App</p>