如何做vue.js项目markdown代码块高亮?

如何做vue.js项目markdown代码块高亮?

使用 marked 进行 markdown 文档的解析,并使用 highlight.js 进行代码块的高亮显示

1. 首先安装相关依赖:

marked.js、marked-extended-tables(表格插件) 和 highlight.js

2. 配置 marked 来解析 markdown 文档,并高亮代码块

一下是可用的配置,md.ts 文件添加了部分语言的支持,更多语言请查看highlight.js的文档,进行引入即可。

// 引入依赖
import { marked } from "marked";
import hljs from "highlight.js/lib/core";

// 引入样式
import "highlight.js/styles/ir-black.css";

// 引入需要的相关语言包
import accesslog from 'highlight.js/lib/languages/accesslog'
import bash from 'highlight.js/lib/languages/bash';
import dockerfile from 'highlight.js/lib/languages/dockerfile';
import javascript from 'highlight.js/lib/languages/javascript';
import handlebars from 'highlight.js/lib/languages/handlebars';
import java from 'highlight.js/lib/languages/java';
import json from 'highlight.js/lib/languages/json';
import nginx from 'highlight.js/lib/languages/nginx';
import shell from 'highlight.js/lib/languages/shell'
import sql from 'highlight.js/lib/languages/sql';
import typescript from 'highlight.js/lib/languages/typescript';
import xml from 'highlight.js/lib/languages/xml';
import yaml from 'highlight.js/lib/languages/yaml';

// 语言包需要注册
hljs.registerLanguage('accesslog', accesslog);
hljs.registerLanguage('bash', bash);
hljs.registerLanguage('dockerfile', dockerfile);
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('json', json);
hljs.registerLanguage('nginx', nginx);
hljs.registerLanguage('handlebars', handlebars);
hljs.registerLanguage('typescript', typescript);
hljs.registerLanguage('java', java);
hljs.registerLanguage('yaml', yaml);
hljs.registerLanguage('sql', sql);
hljs.registerLanguage('shell', shell)
hljs.registerLanguage('xml', xml);

// 配置 marked 的 options 
marked.setOptions({
  renderer: new marked.Renderer(),
  // 高亮代码块配置
  highlight: function (code: string, lang: string) {
    // 设置默认语言(注意需要引入并注册)
    const language = hljs.getLanguage(lang) ? lang : 'sh';
    return hljs.highlight(code, { language }).value;
  },
  pedantic: false,
  gfm: true, // 开启gfm
  breaks: true,
  smartLists: true,
  xhtml: true
})

export default marked