React中Tiptap+Lowlight.js语法高亮解析,react-html-parser失效求助
解决方案
问题核心
管理页通过Tiptap的CodeBlockLowlight插件渲染时,Lowlight已将代码转换为带语法高亮类的嵌套span标签;但博客页的content仅包含原始<pre><code>标签,react-html-parser只会解析HTML结构,不会自动执行语法高亮逻辑,同时内容里的HTML实体转义(如=>)也会导致代码无法被正常识别。
具体解决步骤
1. 引入语法高亮样式
在博客页的入口文件或当前组件中引入高亮样式(以highlight.js的github-dark主题为例,可按需替换):
import 'highlight.js/styles/github-dark.css'
2. 安装依赖包
确保已安装处理HTML实体和语法高亮的工具:
npm install lowlight he
3. 编写代码块处理逻辑
在博客页组件中,通过react-html-parser的transform选项对每个代码块进行高亮处理:
import lowlight from 'lowlight' import he from 'he' import parse from 'react-html-parser' // 处理代码块的transform函数 const transformCodeBlock = (node) => { // 匹配<pre>下的<code>标签 if (node.type === 'tag' && node.name === 'code' && node.parent?.name === 'pre') { // 解码HTML实体(将=>这类转义字符还原为=>) const rawCode = he.decode(node.children[0]?.data || '') // 从class属性提取语言标识(如language-javascript) const language = node.attribs.class?.match(/language-(\w+)/)?.[1] let highlightedResult if (language) { try { // 指定语言进行高亮处理 highlightedResult = lowlight.highlight(language, rawCode) } catch (err) { // 语言不支持时自动检测 highlightedResult = lowlight.highlightAuto(rawCode) } } else { // 无语言标识时自动检测语言 highlightedResult = lowlight.highlightAuto(rawCode) } // 返回处理后的高亮代码块 return ( <code className={`language-${highlightedResult.language}`}> {parse(highlightedResult.value)} </code> ) } // 非代码块节点保持原样 return null }
4. 修改渲染逻辑
将原有的parse(content)替换为带transform选项的调用:
<div className='prose pros-lg max-w-full mx-auto'> <h1>{title}</h1> {parse(content, { transform: transformCodeBlock })} </div>
5. 优化管理页输出(可选)
为让博客页的语言识别更精准,确保管理页的Tiptap配置中,CodeBlockLowlight插件生成带语言类的标签:
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight' import { createLowlight } from 'lowlight' // 按需注册需要支持的编程语言 import javascript from 'lowlight/lib/common/javascript' import python from 'lowlight/lib/common/python' const lowlight = createLowlight() lowlight.register('javascript', javascript) lowlight.register('python', python) // Tiptap扩展配置 extensions: [ CodeBlockLowlight.configure({ lowlight, defaultLanguage: 'javascript', // 设置默认代码语言 }), ]
这样管理页生成的代码块会带有class="language-javascript"这类标识,博客页处理时就能精准匹配语言,提升高亮效果。
内容的提问来源于stack exchange,提问作者Random People
相关产品推荐
相关产品推荐

