最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

前端語法高亮插件Prism.js使用詳細教程

 更新時間:2024年05月25日 15:31:46   作者:零時的輕語者  
最近項目有代碼高亮的需求,這邊是選用Prism.js來進行代碼高亮,Prism是一款輕量級、可擴展的語法高亮器,根據(jù)現(xiàn)代?Web?標準構建,應用廣泛,這篇文章主要給大家介紹了關于前端語法高亮插件Prism.js使用詳細教程的相關資料,需要的朋友可以參考下

介紹

最近項目有代碼高亮的需求,這邊是選用 Prism.js 來進行代碼高亮。

Prism 是一款輕量級、可擴展的語法高亮器,根據(jù)現(xiàn)代 Web 標準構建,應用廣泛。

官網(wǎng):https://prismjs.com/

文檔:https://prismjs.com/docs/index.html

示例

<!DOCTYPE html>
<html>
  <head>
    <!-- 可以通過 CDN 的方式導入 -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Prism Test</title>
    <link  rel="external nofollow"  rel="external nofollow"  rel="stylesheet" />
  </head>
  <body>
    <pre class="line-numbers">
      <code class="language-cpp">
        #include &lt;iostream>
        using namespace std;
          
        struct ListNode {
          int val;
          ListNode *next;
          ListNode() : val(0), next(nullptr) {}
          ListNode(int x) : val(x), next(nullptr) {}
          ListNode(int x, ListNode *next) : val(x), next(next) {}
        };  
      </code>
    </pre>

    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/prism-core.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/plugins/normalize-whitespace/prism-normalize-whitespace.min.js"
      integrity="sha256-ronWqXsvaeyrdiX7YJfdYj0S5NbeMA5ilQQTrK25Jno="
      crossorigin="anonymous"
    ></script>
  </body>
</html>

主題

Prism.js 支持多種主題

插件

Prism.js 有多種插件可以使用,這里介紹幾個常用的插件。

1、show-language

在代碼塊中顯示代碼塊對應語言的名稱

Show Language ▲ Prism plugins:https://prismjs.com/plugins/show-language

<pre>
  <code class="language-js">
    function curry(func) {
      return function curried(...args) {
        if (args.length >= func.length) {
          return func.apply(this, args);
        } else {
          return function(...args2) {
            return curried.apply(this, args.concat(args2));
          }
        }
      };
    }
  </code>
</pre>

2、line-numbers

在代碼塊中顯示行號

Line Numbers ▲ Prism plugins:https://prismjs.com/plugins/line-numbers/

<pre class="line-numbers">
  <code class="language-js">
    function curry(func) {
      return function curried(...args) {
        if (args.length >= func.length) {
          return func.apply(this, args);
        } else {
          return function(...args2) {
            return curried.apply(this, args.concat(args2));
          }
        }
      };
    }
  </code>
</pre>

通過添加  "line-numbers" class 來為代碼塊(<pre><code>)添加行號。

如果將 "line-numbers" class 添加到 <body> 中,則為所有代碼塊(<pre><code>)添加行號。

此外,我們可以使用 "no-line-numbers" class 來移除行號。

3、normalize-whitespace

標準化代碼塊中的空白字符Normalize Whitespace ▲ Prism plugins:https://prismjs.com/plugins/normalize-whitespace/

默認情況下,該插件會裁剪每個代碼塊的所有前端和尾部空白字符,并移除每行上多余的縮進和尾部空白字符。

可以通過添加 "no-whitespace-normalization" class 來阻止該插件生效。

示例代碼

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Prism Test</title>
    <link href="prism.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="stylesheet" />
  </head>
  <body>
    <pre>
      <code class="language-js">
        function curry(func) {
          return function curried(...args) {
            if (args.length >= func.length) {
              return func.apply(this, args);
            } else {
              return function(...args2) {
                return curried.apply(this, args.concat(args2));
              }
            }
          };
        }
      </code>
    </pre>

    <script src="prism.js"></script>
  </body>
</html>

 不使用 normalize-whitespace 插件情況

使用  normalize-whitespace 插件情況

可以看到在使用  normalize-whitespace 插件情況下,代碼塊前端的空白字符被移除,更為美觀。

4、unescaped-markup

編寫標記語言而無需轉(zhuǎn)義任何內(nèi)容

Unescaped markup ▲ Prism plugins:https://prismjs.com/plugins/unescaped-markup/

可以使用 <script type="text/plain" class="language-markup"> 方式

<script type="text/plain" class="language-markup">
  <html></html>
  <p>Example</p>
  <div><button>Hello</button></div>
</script>

 也可以使用 <pre><code class="language-markup"><!-- --></code></pre> 方式

<pre>
  <code class="language-markup"><!--
    <html></html>
    <p>Example</p>
    <div><button>Hello</button></div>
  --></code>
</pre>

5、copy-to-clipboard

添加一個按鈕,可以在單擊時將代碼塊內(nèi)容復制到剪貼板

Copy to Clipboard ▲ Prism plugins:https://prismjs.com/plugins/copy-to-clipboard/默認情況下,插件以英語顯示消息,并設置 5 秒的間隔復制時間。

可以使用以下屬性來覆蓋默認設置:

  • data-prismjs-copy — 默認情況下復制按鈕顯示的文字
  • data-prismjs-copy-error — 復制失敗時顯示的信息
  • data-prismjs-copy-success — 復制成功時顯示的信息
  • data-prismjs-copy-timeout — 兩次復制允許的間隔時間

<pre>
  <code class="language-js" 
    data-prismjs-copy="復制" 
    data-prismjs-copy-error="復制失敗" 
    data-prismjs-copy-success="復制成功"
  >
    let range = new Range();
    range.setStart(p1.firstChild, 2);
    range.setEndAfter(p2.firstChild);
    document.getSelection().addRange(range);
  </code>
</pre>

6、show-invisibles

顯示隱藏字符,例如制表符和換行符

Show Invisibles ▲ Prism plugins:https://prismjs.com/plugins/show-invisibles/

使用

1、直接下載

在下載界面選擇需要的語言和插件,下載 js 和 css, 然后導入使用

Download ▲ Prism:https://prismjs.com/download.html#themes=prism-tomorrow&languages=markup+css+clike+javascript

<!DOCTYPE html>
<html>
  <head>
    ...
    <link href="prism.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="stylesheet" />
  </head>
  <body>
    ...
    <script src="prism.js"></script>
  </body>
</html>

2、CDN 方式

可以使用 cdnjs、jsDelivr 和 UNPKG 等 cdn 導入 PrismJS

<!DOCTYPE html>
<html>
  <head>
    <!-- 通過 CDN 方式導入 -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Prism Test</title>
    <link  rel="external nofollow"  rel="external nofollow"  rel="stylesheet" />
  </head>
  <body>
    <pre class="line-numbers">
      <code class="language-cpp">
        #include &lt;iostream>
        using namespace std;
          
        struct ListNode {
          int val;
          ListNode *next;
          ListNode() : val(0), next(nullptr) {}
          ListNode(int x) : val(x), next(nullptr) {}
          ListNode(int x, ListNode *next) : val(x), next(next) {}
        };  
      </code>
    </pre>

    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/prism-core.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/plugins/normalize-whitespace/prism-normalize-whitespace.min.js"
      integrity="sha256-ronWqXsvaeyrdiX7YJfdYj0S5NbeMA5ilQQTrK25Jno="
      crossorigin="anonymous"
    ></script>
  </body>
</html>

3、Vue3 中使用

npm install prismjs
# 支持 typescript
npm install @types/prismjs -D
npm install vite-plugin-prismjs -D

vite.config.js 中配置

import prismjs from 'vite-plugin-prismjs';
export default defineConfig({
  plugins: [
    prismjs({
      languages: ['javascript', 'css', 'html', 'json', 'sass', 'scss', 'md', 'bash', 'shell', 'ts'],
      plugins: [
        'toolbar',
        'show-language',
        'copy-to-clipboard',
        'normalize-whitespace',
        'line-numbers',
        'unescaped-markup'
      ],
      theme: 'tomorrow',
      css: true
    })
  ],
});

基本使用

<template>
  <pre class="line-numbers">
    <code class='language-js'>
      // JavaScript 代碼
      function curry(func) {
        return function curried(...args) {
          if (args.length >= func.length) {
            return func.apply(this, args);
          } else {
            return function(...args2) {
              return curried.apply(this, args.concat(args2));
            }
          }
        };
      }
    </code>
  </pre>
</template>
<script setup>
import { onMounted } from 'vue';
import Prism from 'prismjs';

onMounted(() => {
  Prism.highlightAll();
});
</script>
<style lang="scss" scoped></style>

補充

API

Prism.js 提供了一些 API

詳見:https://prismjs.com/docs/Prism.html#.manual

如:

highlight(text, grammar, language) → {string}

// 例子
Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');

按鈕樣式調(diào)節(jié)

我們可能對代碼塊右上角按鈕的樣式不太滿意,可以對此進行一定的調(diào)整。

如:

按鈕變?yōu)榉娇?,改變光標類?/p>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Prism Test</title>

    <link href="prism.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="stylesheet" type="text/css" />
    <style>
      body {
        margin: 0;
        padding: 0;
        height: 100vh;
      }
      div.code-toolbar > .toolbar {
        opacity: 1;
      }
      .toolbar .toolbar-item span,
      .toolbar .toolbar-item button {
        border-radius: 0 !important;
        margin: 0 6px;
      }
      .copy-to-clipboard-button:hover {
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <pre class="line-numbers">
      <code class="language-js" 
        data-prismjs-copy="復制" 
        data-prismjs-copy-error="復制失敗" 
        data-prismjs-copy-success="復制成功"
      >
        let range = new Range();
        range.setStart(p1.firstChild, 2);
        range.setEndAfter(p2.firstChild);
        document.getSelection().addRange(range);
      </code>
    </pre>
    <script src="prism.js"></script>
  </body>
</html>

Vue3 代碼高亮組件(僅供參考)

在 Vue3 中無法使用 <script type="text/plain" class="language-markup"> 方式高亮標記語言。

如果需要實現(xiàn)一個代碼高亮組件的話 ,我們可以使用 <pre><code class="language-xxx"></code></pre> + slot  的方式渲染非標記語言;

使用 <pre><code class="language-markup"></code></pre> + props + Prism.highlight +  v-html 來渲染標記語言。

高亮 script 標簽

使用 <script type="text/plain" class="language-markup"> 方式高亮標記語言時,如果要高亮 <script> 標簽則需要轉(zhuǎn)義。

<script type="text/plain" class="language-markup">
  <html></html>
  <p>Example</p>
  <div><button>Hello</button></div>
  <script>&lt;/script>
</script>

此外,在 Vue3 中通過 API 渲染 <script> 標簽時,轉(zhuǎn)義后,可能會引起 eslint 報錯,可以通過配置 'no-useless-escape': 'off' 等方式解決,見 配置規(guī)則 - ESLint - 插件化的 JavaScript 代碼檢查工具

總結(jié)

到此這篇關于前端語法高亮插件Prism.js使用詳細教程的文章就介紹到這了,更多相關前端語法高亮Prism.js使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

  • JS使用正則表達式驗證身份證號碼

    JS使用正則表達式驗證身份證號碼

    這篇文章主要介紹了JS使用正則表達式驗證身份證號碼的相關資料,需要的朋友可以參考下
    2017-06-06
  • js中將String轉(zhuǎn)換為number以便比較

    js中將String轉(zhuǎn)換為number以便比較

    string沒轉(zhuǎn)換就拿去比較,結(jié)果是很頭疼的,下面為大家介紹下js中String轉(zhuǎn)換為number,需要的朋友可以參考下
    2014-07-07
  • 邏輯表達式中與或非的用法詳解

    邏輯表達式中與或非的用法詳解

    這篇文章主要介紹了邏輯表達式中與或非的用法的相關資料,非常不錯具有參考借鑒價值,需要的朋友可以參考下
    2016-06-06
  • 第五章之BootStrap 柵格系統(tǒng)

    第五章之BootStrap 柵格系統(tǒng)

    Bootstrap,來自 Twitter,是目前最受歡迎的前端框架。本文給大家介紹BootStrap 柵格系統(tǒng)的相關資料,需要的朋友可以參考下
    2016-04-04
  • For循環(huán)中分號隔開的3部分的執(zhí)行順序探討

    For循環(huán)中分號隔開的3部分的執(zhí)行順序探討

    這篇文章主要探討了For循環(huán)中分號隔開的3部分的執(zhí)行順序,需要的朋友可以參考下
    2014-05-05
  • Javascript 中文字符串處理額外注意事項

    Javascript 中文字符串處理額外注意事項

    javascript文件中的字符常量與所在的js文件字符編碼密切相關,如下一段代碼
    2009-11-11
  • 前端實現(xiàn)類似chatgpt的對話頁面(案例)

    前端實現(xiàn)類似chatgpt的對話頁面(案例)

    這篇文章主要介紹了前端實現(xiàn)類似chatgpt的對話頁面(案例),需要的朋友可以參考下
    2023-03-03
  • Python版實現(xiàn)微信公眾號掃碼登陸

    Python版實現(xiàn)微信公眾號掃碼登陸

    這篇文章主要介紹了Python版實現(xiàn)微信公眾號掃碼登陸,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-05-05
  • JavaScript原生數(shù)組函數(shù)實例匯總

    JavaScript原生數(shù)組函數(shù)實例匯總

    這篇文章主要介紹了JavaScript原生數(shù)組函數(shù)實例匯總,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-10-10
  • 最新評論

    珲春市| 清河县| 南澳县| 金寨县| 平江县| 福海县| 富阳市| 枣强县| 原阳县| 贡觉县| 噶尔县| 盐池县| 镇沅| 神池县| 延长县| 忻城县| 金堂县| 宁陵县| 龙岩市| 武邑县| 赤壁市| 宜昌市| 文登市| 武平县| 镇坪县| 同仁县| 安岳县| 抚顺市| 恩施市| 克拉玛依市| 富裕县| 三亚市| 久治县| 陈巴尔虎旗| 九寨沟县| 乾安县| 莫力| 宝清县| 上饶市| 高州市| 丹东市|