使用markdown-it怎么配合highlight.js做出自动行号

63 阅读1分钟

ai聊天机器人开发

技术栈 websocket、vue2、markdown-it,highlight.js

常见问题

使用markdown-it怎么配合highlight.js做出自动行号

markdown-it 里配置highlight属性,highlight是一个函数,每次出现代码块的时候都会走这个函数,这个函数有两个参数一个是lang(代码用的语言)一个是str(代码块里的内容)

方法一

方法思路:先把代码内容用highlight.js高亮,高亮后的代码并没有行号,再用ol>li 包裹一层就会有行号了

const md = require("markdown-it")({
  html: true,
  linkify: true,
  typographer: true,
  highlight: (str, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        const preCode = hljs.highlight(lang, str).value;
        const lines = preCode.split("\n").slice(0, -1);//删除末尾空行
        let html = lines
          .map((item, index) => {
            return (
              '<li><span class="line-num" data-line="' +
              (index + 1) +
              '"></span>' +
              item +
              "</li>"
            );
          })
          .join("");
        html = "<ol>" + html + "</ol>";
        if (lines.length) {
          html += '<b class="name">' + lang + "</b>";
        }
        return '<pre class="hljs"><code>' + html + "</code></pre>";
      } catch (__) {
        console.log("Failed to highlight code");
      }
    }

    return "";
  }
});

再修改一下代码样式

.pre-hljs {
  padding: 8px 2px;
  border-radius: 5px;
  position: relative;
}

.pre-hljs ol {
  list-style: decimal;
  margin: 0;
  margin-left: 40px;
  padding: 0;
}

.pre-hljs ol li {
  list-style: decimal-leading-zero;
  position: relative;
  padding-left: 10px;
}

.pre-hljs ol li .line-num {
  position: absolute;
  left: -40px;
  top: 0;
  width: 40px;
  height: 100%;
  border-right: 1px solid rgba(0, 0, 0, 0.66);
}

.pre-hljs b.name {
  position: absolute;
  top: 2px;
  right: 12px;
  z-index: 10;
  color: #999;
  pointer-events: none;
}

效果如下:

image.png

但是行号样式不好调,后面加了一个点为了修改我们使用伪类的方法调整