2024-07-16 代码高亮插件highlight.js安装使用以及排错日志

highlight.js —— 一个开源语法高亮库,用于在网页上对源代码进行语法高亮显示。
安装
npm i highlight.js
yarn add highlight.js

引入

// main.js
import { createApp } from 'vue';
import App from "./App.vue";
import hljs from "highlight.js"; // 代码高亮插件
import "highlight.js/styles/color-brewer.css" // 引入高亮样式

const app = createApp(App);
// 自定义指令
app.directive("highlight", function (el) {
    const blocks = el.querySelectorAll("pre code");
    blocks.forEach((el2: any) => {
        hljs.highlightElement(el2);
    });
});
app.mount('#app');

使用

<pre v-highlight>
    <code class="language-javascript">
        {{ code }}                      
    </code>
</pre>

效果预览:

报错:

1):

Deprecated as of 10.7.0. highlightBlock will be removed entirely in v12.0.(自10.7.0起弃用。highlightBlock将在v12.0中完全删除)

Deprecated as of 10.7.0. Please use highlightElement now.(自10.7.0起弃用。请立即使用highlightElement。)

原因:highlightBlock方法废弃了,改为highlightElement吧。

如果你的版本低于上面的提示版本,那就得改了,我的是最新的。

2):WARN: Could not find the language 'undefined', did you forget to load/include a language module?(警告:找不到语言“undefined”,是否忘记加载/包含语言模块?)

原因:你要在代码块的一个类名写上诸如class="language-javascript"的标识,它highlight.js才能识别,通常是这么写:

 <code class="language-javascript">
    // ...
 </code>

3):Element previously highlighted. To highlight again, first unset dataset.highlighted.(之前突出显示的元素。要再次突出显示,请先将未设置的数据集高亮显示。)

解决方案:重启服务,这个我觉得是在开发中应该会遇到过,至少现在是这样。

ps:我上面的代码已经是改好的了,坑我已经踩了。

 

posted @ 2024-07-16 15:08  叶乘风  阅读(29)  评论(0编辑  收藏  举报