V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
simonguo
V2EX  ›  React

将 Markdown 文件导入为 React 组件 - 写作文档,即时获取交互式演示

  •  
  •   simonguo · 3 天前 · 1207 次点击

    我最近将 react-code-view 进行了重写, 基于 unplugin 让 Markdown 可以直接导入渲染成一个 React 组件. 以下是一个简单示例

    1.安装

    npm install @react-code-view/react @react-code-view/unplugin
    

    2.配置构建工具(支持 vite/webpack/esbuild/rollup)

    // vite.config.js
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import reactCodeView from '@react-code-view/unplugin/vite';
    
    export default defineConfig({
      plugins: [
        react(),
        reactCodeView() // Enable markdown import
      ]
    });
    

    使用有代码块创建 Markdown 文件

    demo.md

    # Counter Example
    
    
    A simple counter to demonstrate live code editing and preview.
    
    
    <!--start-code-->
    \`\`\`jsx
    const App = () => {
      const [count, setCount] = useState(0);
      return (
        <button onClick={() => setCount(c => c + 1)}>
          Clicked {count} times
        </button>
      );
    };
    
    render(<App />);
    \`\`\`
    <!--end-code-->
    
    - Click "Show Code" to view and edit the source
    - Preview updates instantly while you type
    - Click the copy button to reuse the code
    

    4.导入并使用

    import Demo from './demo.md';
    
    function App() {
      return <Demo />;
    }
    

    最好渲染成的效果

    文档

    目前尚无回复
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   870 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 23:08 · PVG 07:08 · LAX 15:08 · JFK 18:08
    ♥ Do have faith in what you're doing.