给博客加上代码高亮(不引外部库)
博客免不了贴代码。常见做法是引 highlight.js,但它会带来两个负担:访客要多下载几百 KB 的 JS,而且通常从 CDN 加载——服务器带宽小、又不想依赖外部网络的时候就很别扭。
思路:服务端切 token
核心其实很简单:在服务端把代码切成「注释 / 字符串 / 关键字 / 数字」这几类片段,各自包上 <span class="tok-xxx">,颜色交给 CSS。未被任何规则命中的字符当普通文本处理。
jsfunction highlight(code, lang) {
const marks = new Array(code.length).fill(null);
for (const { type, re } of rulesFor(lang)) {
re.lastIndex = 0;
let m;
while ((m = re.exec(code)) !== null) {
// 已被更早的规则标记过的位置不覆盖(注释优先级最高)
let free = true;
for (let i = m.index; i < m.index + m[0].length; i++) {
if (marks[i] !== null) { free = false; break; }
}
if (free) {
for (let i = m.index; i < m.index + m[0].length; i++) marks[i] = type;
}
}
}
// 把连续的同类片段合并后输出,顺便做 HTML 转义
}
两个关键细节
规则顺序很重要
注释必须排在关键字前面,否则 // const 里的 const 会被当成关键字染色:
jsconst rules = [
{ type: 'comment', re: /\/\/[^\n]*/g },
{ type: 'string', re: /"[^"]*"/g },
{ type: 'keyword', re: /\b(?:const|let|function|return)\b/g },
];
一定要转义
代码里出现 <script> 是常态,不转义就等于自己开了个 XSS 口子:
jsconst escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
}[c]));
效果与取舍
现在支持 JS / TS / Python / Shell / Go / SQL / HTML / CSS 等十几种语言,压缩后不到 4KB,而且是服务端渲染——访客打开就有颜色,不需要等 JS 执行。
代价是不如 highlight.js 精确(复杂语法可能有小瑕疵),但对博客里常见的代码片段完全够用。
评论 0
还没有评论,来说点什么吧。
本站已关闭评论。