【prismjs 】 vite2, vue3 使用配置

段干德泽
2023-12-01

安装


# prismjs 
npm i prismjs -S

# prismjs 类型
npm i -D @types/prismjs

# vite
npm install babel-plugin-prismjs -D

# bable webpack
npm install vite-plugin-prismjs -D

配置

babel

// babel.config.js
module.exports = {
  plugins: [
    [
      'prismjs',
      {
        languages: ['json'],
        // languages: allLanguages,
      },
    ],
  ],
};

vite

// vite.config.js
import { defineConfig } from 'vite';
import prismjs from 'vite-plugin-prismjs';

export default defineConfig({
  plugins: [
    prismjs({
      languages: ['json'],
      //  languages: 'all',
    }),
  ],
});

组件

  • PreviewCode .vue
<template>
 <pre>
    <code  :class="'language-'+ type" v-html="Prism.highlight(code, Prism.languages[type], type)"></code>
 </pre>
 
</template>

<script setup lang="ts">
import { onMounted } from 'vue';

import Prism from 'prismjs';
const props = defineProps({
  code: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'html'
  }
})
const {code, type} = props

</script>

使用

<template>
  <div>
    <PreviewCode :code="code" :type="type" />
  </div>
</template>
 
<script setup lang="ts">
import { ref, reactive } from 'vue'
import PreviewCode from './PreviewCode.vue';

// 高亮语言类型, 如果配置不是 all 的话, 这个类型需要加在配置中
const type = "html"

// 高亮代码
const code =`<target><!-- 模拟数据 -->
      <target>var data = 1</target><target>var data = 1</target>
      <target>var data = 1</target><target>var data = 1</target>
      <target>var data = 1</target><target>var data = 1</target>
      <target>var data = 1</target>
      </target>`
</script>

结语

 类似资料: