主要react+vite项目当中用到,因为vite不能用raw-loader这个webpack-loader,又因为vite-plugin-string这个处理文件的时候无法准确地处理换行的问题,所以发现vite-plugin-markdown这个插件好用。vue+vite显示markdown文件预览内容同上。
1.需要用的库:vite-plugin-markdown,这个库可以将md文件正确import,并输出成markdown格式的组件或字符串
注意这个库官方的引导和示例一团糟,建议参考我这个:
vite.config.js
import { plugin as markdownPlugin, Mode } from "vite-plugin-markdown";
plugins: [
react(),
markdownPlugin({
mode: [Mode.MARKDOWN, Mode.HTML, Mode.REACT], // here need define modes
}),
]
2.需要用到其他的两个库,来处理markdown的显示,其实上面vite-plugin-markdown 这个库是可以直接展示,但我想要更加灵活
- react-markdown emark-gfm 这两个库主要拿来结构化展示markdown内容
- react-syntax-highlighter vscDarkPlus github-markdown-css/github-markdown.css 后面这几个主要是为了高亮和样式~
具体demo
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism";
import { markdown as Terms1_MARKDOWN } from "../../docs/reactcontext.md";
import "github-markdown-css/github-markdown.css";
import "./index.css";
const markdownPaths = {
reactcontext: Terms1_MARKDOWN,
};
const MarkdownReader = (props) => {
const curMarkdownContent = markdownPaths[props.markdown];
// 自定义渲染代码块
const components = {
code: (obj) => {
const { node, inline, className, children, value } = obj;
const match = /language-(\w+)/.exec(className || "");
let language = "javascript";
if (match) {
language = match[1] || "javascript";
return (
<SyntaxHighlighter language={language} style={vscDarkPlus}>
{children}
</SyntaxHighlighter>
);
} else {
return (
<span>{children}</span>
);
}
},
};
return (
<div className="markdown-body" style={{ margin: "0 auto", width: "80%" }}>
<ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
{curMarkdownContent}
</ReactMarkdown>
</div>
);
};
export default MarkdownReader;
仅做参考吧~