Highlight.js 让 Web 网页中代码语法高亮
Highlight.js 是一个代码语法高亮的插件,他在任何浏览器和服务器上都可以工作,几乎可以语法高亮标记任何语言,不依赖任何第三方框架,具有自动识别编程语言的功能。
特点
Highlight.js 是一款轻量级的 Web 代码语法高亮库,它主要有以下几个特点:
- 支持118种语言(看这里https://github.com/isagalaev/highlight.js/tree/master/src/languages)
54中样式(看这里https://github.com/isagalaev/highlight.js/tree/master/src/styles); - 可以自动检测编程语言;
- 同时为多种编程语言代码高亮;
- 支持在 node.js 服务端使用
- 支持任何标签
- 与任何 js 框架兼容。
使用方法
在网页中使用只需要引入相关的文件,然后调用 initHighlightingOnLoad 方法
<link rel="stylesheet" href="/path/to/styles/default.css">
<script src="/path/to/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
他将查找网页中的 <pre><code> 元素,并且语法高亮里面的代码,它尝试自动检测语言。如果自动检测不起作用,则可以在 class 属性中指定语言:
<pre><code class="html">...</code></pre>
Class 类的前缀也可以使用 language- 或者 lang- :
<pre><code class="language-html">...</code></pre>
明文和禁用高亮
如果是普通的文本,要设置代码的样式而不显示高亮,可以使用 nohighlight 类:
<pre><code class="nohighlight">...</code></pre>
支持的语言
下表显示了与库绑定的受支持语言(和相应类)的完整列表。注意:哪些语言可用可能取决于您如何在应用程序中构建或包含库。请参阅下面的“获取库”。
Language | Classes | Package |
---|---|---|
1C | 1c | |
ABNF | abnf | |
Access logs | accesslog | |
Ada | ada | |
ARM assembler | armasm, arm | |
AVR assembler | avrasm | |
ActionScript | actionscript, as | |
Alan | alan, i | highlightjs-alan |
AngelScript | angelscript, asc | |
Apache | apache, apacheconf | |
AppleScript | applescript, osascript | |
Arcade | arcade | |
AsciiDoc | asciidoc, adoc | |
AspectJ | aspectj | |
AutoHotkey | autohotkey | |
AutoIt | autoit | |
Awk | awk, mawk, nawk, gawk | |
Axapta | axapta | |
Bash | bash, sh, zsh | |
Basic | basic | |
BNF | bnf | |
Brainfuck | brainfuck, bf | |
C# | cs, csharp | |
C++ | cpp, c, cc, h, c++, h++, hpp | |
C/AL | cal | |
Cache Object Script | cos, cls | |
CMake | cmake, cmake.in | |
Coq | coq | |
CSP | csp | |
CSS | css | |
Cap’n Proto | capnproto, capnp | |
Clojure | clojure, clj | |
CoffeeScript | coffeescript, coffee, cson, iced | |
Crmsh | crmsh, crm, pcmk | |
Crystal | crystal, cr | |
Cypher (Neo4j) | cypher | highlightjs-cypher |
D | d | |
DNS Zone file | dns, zone, bind | |
DOS | dos, bat, cmd | |
Dart | dart | |
Delphi | delphi, dpr, dfm, pas, pascal, freepascal, lazarus, lpr, lfm | |
Diff | diff, patch | |
Django | django, jinja | |
Dockerfile | dockerfile, docker | |
dsconfig | dsconfig | |
DTS (Device Tree) | dts | |
Dust | dust, dst | |
Dylan | dylan | highlight-dylan |
EBNF | ebnf | |
Elixir | elixir | |
Elm | elm | |
Erlang | erlang, erl | |
Excel | excel, xls, xlsx | |
Extempore | extempore, xtlang, xtm | highlightjs-xtlang |
F# | fsharp, fs | |
FIX | fix | |
Fortran | fortran, f90, f95 | |
G-Code | gcode, nc | |
Gams | gams, gms | |
GAUSS | gauss, gss | |
GDScript | godot, gdscript | highlightjs-gdscript |
Gherkin | gherkin | |
GN for Ninja | gn, gni | highlightjs-GN |
Go | go, golang | |
Golo | golo, gololang | |
Gradle | gradle | |
Groovy | groovy | |
HTML, XML | xml, html, xhtml, rss, atom, xjb, xsd, xsl, plist, svg | |
HTTP | http, https | |
Haml | haml | |
Handlebars | handlebars, hbs, html.hbs, html.handlebars | |
Haskell | haskell, hs | |
Haxe | haxe, hx | |
Hy | hy, hylang | |
Ini, TOML | ini, toml | |
Inform7 | inform7, i7 | |
IRPF90 | irpf90 | |
JSON | json | |
Java | java, jsp | |
JavaScript | javascript, js, jsx | |
Kotlin | kotlin, kt | |
Leaf | leaf | |
Lasso | lasso, ls, lassoscript | |
Less | less | |
LDIF | ldif | |
Lisp | lisp | |
LiveCode Server | livecodeserver | |
LiveScript | livescript, ls | |
Lua | lua | |
Makefile | makefile, mk, mak | |
Markdown | markdown, md, mkdown, mkd | |
Mathematica | mathematica, mma, wl | |
Matlab | matlab | |
Maxima | maxima | |
Maya Embedded Language | mel | |
Mercury | mercury | |
mIRC Scripting Language | mirc, mrc | highlightjs-mirc |
Mizar | mizar | |
Mojolicious | mojolicious | |
Monkey | monkey | |
Moonscript | moonscript, moon | |
N1QL | n1ql | |
NSIS | nsis | |
Nginx | nginx, nginxconf | |
Nimrod | nimrod, nim | |
Nix | nix | |
OCaml | ocaml, ml | |
Objective C | objectivec, mm, objc, obj-c | |
OpenGL Shading Language | glsl | |
OpenSCAD | openscad, scad | |
Oracle Rules Language | ruleslanguage | |
Oxygene | oxygene | |
PF | pf, pf.conf | |
PHP | php, php3, php4, php5, php6 | |
Parser3 | parser3 | |
Perl | perl, pl, pm | |
Plaintext: no highlight | plaintext | |
Pony | pony | |
PostgreSQL & PL/pgSQL | pgsql, postgres, postgresql | |
PowerShell | powershell, ps, ps1 | |
Processing | processing | |
Prolog | prolog | |
Properties | properties | |
Protocol Buffers | protobuf | |
Puppet | puppet, pp | |
Python | python, py, gyp | |
Python profiler results | profile | |
Q | k, kdb | |
QML | qml | |
R | r | |
Razor CSHTML | cshtml, razor, razor-cshtml | highlightjs-cshtml-razor |
ReasonML | reasonml, re | |
RenderMan RIB | rib | |
RenderMan RSL | rsl | |
Roboconf | graph, instances | |
Robot Framework | robot, rf | highlightjs-robot |
RPM spec files | rpm-specfile, rpm, spec, rpm-spec, specfile | highlightjs-rpm-specfile |
Ruby | ruby, rb, gemspec, podspec, thor, irb | |
Rust | rust, rs | |
SAS | SAS, sas | |
SCSS | scss | |
SQL | sql | |
STEP Part 21 | p21, step, stp | |
Scala | scala | |
Scheme | scheme | |
Scilab | scilab, sci | |
Shape Expressions | shexc | highlightjs-shexc |
Shell | shell, console | |
Smali | smali | |
Smalltalk | smalltalk, st | |
Solidity | solidity, sol | highlightjs-solidity |
Stan | stan | |
Stata | stata | |
Structured Text | iecst, scl, stl, structured-text | highlightjs-structured-text |
Stylus | stylus, styl | |
SubUnit | subunit | |
Supercollider | supercollider, sc | highlightjs-supercollider |
Swift | swift | |
Tcl | tcl, tk | |
Terraform (HCL) | terraform, tf, hcl | highlightjs-terraform |
Test Anything Protocol | tap | |
TeX | tex | |
Thrift | thrift | |
TP | tp | |
Twig | twig, craftcms | |
TypeScript | typescript, ts | |
VB.Net | vbnet, vb | |
VBScript | vbscript, vbs | |
VHDL | vhdl | |
Vala | vala | |
Verilog | verilog, v | |
Vim Script | vim | |
x86 Assembly | x86asm | |
XL | xl, tao | |
XQuery | xquery, xpath, xq | |
YAML | yml, yaml | |
Zephir | zephir, zep |
具有指定包名称的语言在单独的存储库中定义,不包含在 highlight.pack.js 文件中。
自定义初始化
当需要对 highlight.js 的初始化进行更多控制时,比如你的代码是动态生成的,那么可以使用 highlightBlock 和 configure 函数。这允许您控制突出显示的内容和高亮显示的时间。
下面是使用 vanilla JS 调用 initHighlightingOnLoad 的等效方法:
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('pre code').forEach((block) => {
hljs.highlightBlock(block);
});
});
您可以使用任何标记而不是<pre><code>来标记您的代码。如果不使用保留换行符的容器,则需要配置highlight.js以使用<br>标记:
hljs.configure({useBR: true});
document.querySelectorAll('div.code').forEach((block) => {
hljs.highlightBlock(block);
});
更多的可选参数,请参加 configure 帮助文档。
网页 Web 线程
您可以在一个 Web 线程内部运行高亮显示,以避免在处理非常大的代码块时冻结浏览器窗口。你可以这样编写代码:
addEventListener('load', () => {
const code = document.querySelector('#code');
const worker = new Worker('worker.js');
worker.onmessage = (event) => { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
});
worker.js 文件代码:
onmessage = (event) => {
importScripts('<path>/highlight.pack.js');
const result = self.hljs.highlightAuto(event.data);
postMessage(result.value);
};
在 Node.js 中使用
在将内容发送到浏览器之前,可以将 highlight.js 与 Node.js 一起用于高亮显示代码内容。请确保使用 .value 属性获取格式化的 html。有关返回对象的更多信息,请参阅 API 文档https://highlightjs.readthedocs.io/en/latest/api.html
// require the highlight.js library including all languages
const hljs = require('./highlight.js');
const highlightedCode = hljs.highlightAuto('<span>Hello World!</span>').value
// require the highlight.js library without languages
const hljs = require("highlight.js/lib/highlight.js");
// separately require languages
hljs.registerLanguage('html', require('highlight.js/lib/languages/html'));
hljs.registerLanguage('sql', require('highlight.js/lib/languages/sql'));
// highlight with providing the language
const highlightedCode = hljs.highlight('html', '<span>Hello World!</span>').value
获取代码
可以将 highlight.js 作为托管、自定义生成、浏览器脚本或服务器模块。开箱即用的浏览器脚本同时支持AMD和CommonJS,因此如果您希望使用RequireJS或Browserify,无需从源代码构建。服务器模块也可以与Browserify一起完美地工作,但是可以选择使用特定于浏览器的构建,而不是针对服务器的构建。进入下载页面查看所有选项。
不要直接链接到 GitHub 的 JS 文件。GitHub 只是代码托管,而不是作为 CDN 加速,而且源代码需要构建编辑。如果打包的选项都不适用,请参阅构建编译文档。
CDN 托管的包没有所有的语言。否则就文件就太大了。如果在常用部分看不到所需的语言,可以手动添加:
<script
charset="UTF-8"
src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.9/languages/go.min.js"
></script>
在 Almond 上,你需要使用优化器为模块命名,比如:
r.js -o name=hljs paths.hljs=/path/to/highlight out=highlight.js
CommonJS
You can import Highlight.js as a CommonJS-module:
npm install highlight.js --save
In your application:
import hljs from 'highlight.js';
The default import imports all languages! Therefore it is likely to be more efficient to import only the library and the languages you need:
import hljs from 'highlight.js/lib/highlight';
import javascript from 'highlight.js/lib/languages/javascript';
hljs.registerLanguage('javascript', javascript);
To set the syntax highlighting style, if your build tool processes CSS from your JavaScript entry point, you can import the stylesheet directly into your CommonJS-module:
import hljs from 'highlight.js/lib/highlight';
import 'highlight.js/styles/github.css';
License
Highlight.js is released under the BSD License. See LICENSE file for details.
相关链接
The official site for the library is at https://highlightjs.org/.
Further in-depth documentation for the API and other topics is at http://highlightjs.readthedocs.io/.
Authors and contributors are listed in the AUTHORS.en.txt file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论