从markdown-it到mdx,讲讲遇到的一些小问题

发表于 2023-08-04 | 前端

markdown

一直习惯用markdown写博客,因为很简单的语法就能生成好看的格式。如果你只是想一个结果,那是一个很简答的事情,但是你想要一个舒服的过程,就很难。

mdx和next-mdx-remote

因为用的是nextjs所以首先想到的就是mdx,但是mdx只能加载文件,所以了解到了社区插件next-mdx-remote,他能转换内容。

rehype-pretty-code、rehype-toc和rehype-slug

markdown里的代码渲染首先想到的是highlightjs,而rehype-pretty-code的优点是在于可以服务端渲染。 rehype-toc可以生成目录,rehype-slug可以增加锚点,都是可以服务端渲染,缺点是很难定义它出现的位置,所以我用了fixed这个css属性。

实际使用

mdx是有nextj是有官网详细配置的。 我这里使用的是next-mdx-remote,不需要mdx的任何配置,也不需要mdx的包,只导入next-mdx-remote就好了

<MDXRemote
	source={blogInfo.article.context}
	options={{
		parseFrontmatter: true,
		mdxOptions: {
			rehypePlugins: [rehypeSlug, [rehypePrettyCode, {
				theme: 'one-dark-pro',
			}], [toc, {
				cssClasses: {
					list: 'toc-list',
					listItem: 'toc-list-item'
				},
				customizeTOC: (tocAll: HtmlElementNode) => {
					return {
						type: "element",
						tagName: "div",
						properties: {className: "toc-container h-[89%] not-prose"},
						children: [tocAll],
					};
				}
			}]],
		},
	}}
/>

这里使用了one-dark-pro主题,会出现奇怪的,build后找不到主题问题。 所以我这里在官方推荐dockerfile里增加了COPY --from=builder --chown=1001:1001 /app/node_modules/shiki ./node_modules/shiki 把外部的node_modules的shiki,拷贝到打包后的shiki文件