highlight.js Syntax highlighting for the Web
译文:highlight.js为Web突出显示语法
文档
1、方式一:cdn
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
2、方式二:npm
npm install highlight.js
示例
hljs = require('highlight.js');
html = hljs.highlightAuto('<h1>Hello World!</h1>').value
3、方式三:ESM
import hljs from 'highlight.js';
import javascript from 'highlight.js/lib/languages/javascript';
hljs.registerLanguage('javascript', javascript);
// 或者
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
安装
pnpm i -S @highlightjs/vue-plugin
示例
import 'highlight.js/styles/stackoverflow-light.css'
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import hljsVuePlugin from "@highlightjs/vue-plugin";
hljs.registerLanguage('javascript', javascript);
const app = createApp(App)
app.use(hljsVuePlugin)
app.mount('#app')
<div id="app">
<!-- bind to a data property named `code` -->
<highlightjs autodetect :code="code" />
<!-- or literal code works as well -->
<highlightjs language='javascript' code="var x = 5;" />
</div>
示例效果
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>prism demo</title>
<link
rel="stylesheet"
href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css"
/>
</head>
<body>
<h2>javascript</h2>
<pre><code class="language-javaScript">let user = {
"name": "Tom",
"age": 18
};
console.log("hello world!");</code></pre>
<h2>css</h2>
<pre><code class="language-css">p { color: red }</code></pre>
<script src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</body>
</html>