vue中prismjs实现代码高亮展示行号

1,801 阅读1分钟

prims官网 prismjs.com/

HTML中直接使用Prism.js

官网上选配需要的语言和主题,插件可选行号

image.png

image.png 可以看到 prism.js 非常轻量。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="prism.css" rel="stylesheet" />
  </head>
  <body>
    <pre class="line-numbers"><code class="language-css">p { color: red }</code></pre>
    <script>
        window.Prism = window.Prism || {};
        window.Prism.manual = false;
        </script>
    <script  src="prism.js"></script>
  </body>
</html>

在 vue 中使用

npm install --save prismjs
npm install babel-plugin-prismjs -D

// babelrc/babel.config.js中增加插件
plugins: [
    ['prismjs', {
      'languages': ['javascript', 'java', 'css', 'markup', 'python'],
      'plugins': ['line-numbers'],
      'theme': 'tomorrow',
      'css': true
    }]
  ]

指定使用languages和plugins,以及支持哪些主题。babel将自动添加的插件以及所需的 CSS

// 组件中使用
//main.js
import Prism from 'prismjs'
import 'prismjs/themes/prism.css'

Vue.prototype.Prism = Prism

// 组件中
<template>
<pre class="language-js line-numbers codeTree">
    <code v-html="codeContent" />
</pre>
</template>
<script>
this.codeContent = this.Prism.highlight(
  this.detailData[this.codeKey],
  this.Prism.languages.js
)
// 此处设置异步才能设置代码行号和主题
this.$nextTick(() => {
  this.Prism.highlightAll()
})
</script>
<style>
pre[class*="language-"] {
  padding: 0;
  margin: 0;
}
// 全局设置行号样式才能展示white-space: pre-wrap
pre.line-numbers, pre.no-line-numbers
{
  white-space: pre-wrap;
}
</style>

最后实现效果 image.png