您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

js:highlight.js实现代码的语法高亮

时间:05-24来源:作者:点击数:

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';

Vue.js

安装

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>

支持的语言:https://ghproxy.com/https://raw.githubusercontent.com/highlightjs/highlight.js/main/SUPPORTED_LANGUAGES.md

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门