我最近将 react-code-view 进行了重写, 基于 unplugin 让 Markdown 可以直接导入渲染成一个 React 组件. 以下是一个简单示例
1.安装
sql
npm install @react-code-view/react @react-code-view/unplugin
2.配置构建工具(支持 vite/webpack/esbuild/rollup)
javascript
// 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
]
});
3.使用有代码块创建 Markdown 文件
xml
# 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.导入并使用
tsx
import Demo from './demo.md';
function App() {
return <Demo />;
}
最好渲染成的效果
