代码高亮,增强代码的可读性
Highlight
ts 类似 propTypes.oneOf 的属性
https://stackoverflow.com/questions/45251664/derive-union-type-from-tuple-array-values
import React, { useMemo, memo } from 'react';
import { Highlight } from '@ant-design/pro-editor';
import type { HighlightProps } from '@ant-design/pro-editor/es/Highlight/defalut';
export const LanguageTypes = [
"javascript",
"typescript",
"css",
"java",
"json",
"markdown",
"xml",
"yaml",
"python",
"sql",
] as const;
interface IProps extends Omit<HighlightProps, "language"> {
code: string | object;
language?: typeof LanguageTypes[number];
}
function HighlightCode(props: IProps) {
const {
code,
language = 'json',
theme = 'light',
type = 'pure',
lineNumber = true,
containerWrapper = true,
} = props;
const codeString = useMemo(() => {
const isObject: boolean = !!code && typeof code === 'object';
return isObject ? JSON.stringify(code, null, 2) : code;
}, [code]);
return (
<Highlight
language={language}
theme={theme}
type={type}
lineNumber={lineNumber}
containerWrapper={containerWrapper}
>
{codeString}
</Highlight>
);
}
export default memo(HighlightCode);
如果 Omit 报错,tsconfig.json compilerOptions 添加
"typeRoots": [
"./node_modules/@types"
],
�
language 高亮语言
- javascript
- typescript
- css
- java
- json
- markdown
- xml
- yaml
- python
- sql
shiki
轻量级的,代码高亮库
https://github.com/shikijs/shiki
react-syntax-highlighter
https://github.com/react-syntax-highlighter/react-syntax-highlighter
https://www.npmjs.com/package/react-syntax-highlighter
react-syntax-highlighter@15.5.0 包大小
https://react-syntax-highlighter.github.io/react-syntax-highlighter/demo/
细节点:
需要按需加载,默认会加载所有语言,导致体积很大
prismjs代码高亮
https://prismjs.com
prism-json.js
Prism.languages.json = {
'property': /"(?:\\.|[^\\"\r\n])*"(?=\s*:)/i,
'string': {
pattern: /"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
greedy: true
},
'number': /\b0x[\dA-Fa-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?/,
'punctuation': /[{}[\]);,]/,
'operator': /:/g,
'boolean': /\b(?:true|false)\b/i,
'null': /\bnull\b/i
};
Prism.languages.jsonp = Prism.languages.json;
highlight.js
https://github.com/highlightjs/highlight.js
https://highlightjs.org/
BSD-3-Clause license
未经事先书面许可,不得使用著作权人或其贡献者的姓名或名称来宣传或推广由本软件衍生的产品
https://www.ruanyifeng.com/blogimg/asset/201105/bg2011050101.png
zsh-syntax-highlighting
终端命令行代码高亮
https://github.com/zsh-users/zsh-syntax-highlighting