Skip to content

CodeHighlighter 代码高亮

用于高亮代码格式,对齐 @ant-design/x CodeHighlighter

何时使用

  • 用于展示带语法高亮的代码片段,并提供复制功能及头部语言信息。
  • 可与 Markdown / 对话气泡等内容组合,增强代码块展示与交互。

代码演示

基本

基础用法,支持多种语言与 prismLightMode 轻量模式。

JavaScript Code

javascript
import { ref } from 'vue';
import { Button } from 'ant-design-vue';

const App = () => {
  const count = ref(0);
  return (
    <div>
      <Button type="primary" onClick={() => count.value++}>
        Primary Button {count.value}
      </Button>
    </div>
  );
};

export default App;

CSS Code

css
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

HTML Code

html
<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
</head>
<body>
  <h1>Hello World</h1>
</body>
</html>

Prism Light Mode

使用 prismLightMode 属性启用轻量模式,按需加载语言支持,可显著减少打包体积。

javascript
import { ref } from 'vue';
import { Button } from 'ant-design-vue';

const App = () => {
  const count = ref(0);
  return (
    <div>
      <Button type="primary" onClick={() => count.value++}>
        Primary Button {count.value}
      </Button>
    </div>
  );
};

export default App;

自定义 Header

通过 header 自定义头部内容。

Vue 计数器示例
TypeScript
import { ref } from 'vue';

function useCounter() {
  const count = ref(0);
  const increase = () => {
    count.value += 1;
  };
  return { count, increase };
}

API

CodeHighlighterProps

属性说明类型默认值版本
lang代码语言类型string--
children代码内容(也可通过默认插槽传入)string--
header头部内容;为 false / null 时不显示头部VNode | string | (() => VNode | string | false | null) | false | null--
highlightProps透传到 pre 的额外属性object--
prismLightMode是否使用 Prism 轻量模式,按 lang 按需加载语言booleantrue-
classNames语义化结构 classNameRecord<'root' | 'header' | 'headerTitle' | 'code', string>--
styles语义化结构 styleRecord<'root' | 'header' | 'headerTitle' | 'code', CSSProperties>--

CodeHighlighterRef

属性说明类型
nativeElement获取原生 DOM 节点HTMLDivElement | null

CodeHighlighterSlots

插槽名说明
default代码内容
header自定义头部

说明

  • 底层使用 prismjs 做语法高亮(React 版为 react-syntax-highlighter)。
  • 默认头部使用 Typography.Textcopyable 提供复制(React 版为 Actions.Copy)。
  • prismLightMode={false} 会预加载一组常用语言,便于减少首次切换语言的等待。

贡献者

贡献者

正在加载贡献者信息...