最近想用 Vuepress 搭建个人博客,因为 VuePress 是一个以 Markdown 为中心的静态网站生成器,正好可以用来发布 Markdown 笔记,但是使用后发现 Vuepress 对 Markdown 语言的支持一般,特别是不支持 LaTex 公式。好在 Vuepress 支持 Markdown 插件扩展,进而可以支持 LaTex 公式,但其中有一些坑,经过一晚上的探索以后终于成功在浏览器中渲染出来了。
在 Vuepress 项目中安装 markdown-it-katex
yarn add markdown-it-katex 2. 进入 config.ts,项目结构如下
├─ docs
│ ├─ .vuepress
│ │ └─ config.ts
│ └─ README.md
├─ .gitignore
└─ package.json 3. 在 config.ts 的 defineUserConfig 中写入如下配置
export default defineUserConfig<DefaultThemeOptions, ViteBundlerOptions>({
// ,,,
// other configs
extendsMarkdown: md => {
md.use(require('markdown-it-katex'))
md.linkify.set({ fuzzyEmail: false })
},
// other configs
// ...
}) 4. 在 .vuepress 目录中创建 styles 目录,并新建 index.scss 文件,目录结构如下
├─ docs
│ ├─ .vuepress
│ │ ├─ styles
│ │ │ └─ index.scss
│ │ └─ config.ts
│ └─ README.md
├─ .gitignore
└─ package.json 5. 在 index.scss 文件中引入 css 文件
@import "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css";
@import "https://cdn.jsdelivr.net/github-markdown-css/2.2.1/github-markdown.css"; 6. 在 README.md 中输入公式测试
# Maxwell's Equations
equation | description
----------|------------
$\nabla \cdot \vec{\mathbf{B}} = 0$ | divergence of $\vec{\mathbf{B}}$ is zero
$\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} = \vec{\mathbf{0}}$ | curl of $\vec{\mathbf{E}}$ is proportional to the rate of change of $\vec{\mathbf{B}}$
$\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} = \frac{4\pi}{c}\vec{\mathbf{j}} \nabla \cdot \vec{\mathbf{E}} = 4 \pi \rho$ | _wha?_
 运行项目后应该能正常显示 LaTex 公式
