代码高亮,增强代码的可读性

Highlight

ts 类似 propTypes.oneOf 的属性
https://stackoverflow.com/questions/45251664/derive-union-type-from-tuple-array-values

  1. import React, { useMemo, memo } from 'react';
  2. import { Highlight } from '@ant-design/pro-editor';
  3. import type { HighlightProps } from '@ant-design/pro-editor/es/Highlight/defalut';
  4. export const LanguageTypes = [
  5. "javascript",
  6. "typescript",
  7. "css",
  8. "java",
  9. "json",
  10. "markdown",
  11. "xml",
  12. "yaml",
  13. "python",
  14. "sql",
  15. ] as const;
  16. interface IProps extends Omit<HighlightProps, "language"> {
  17. code: string | object;
  18. language?: typeof LanguageTypes[number];
  19. }
  20. function HighlightCode(props: IProps) {
  21. const {
  22. code,
  23. language = 'json',
  24. theme = 'light',
  25. type = 'pure',
  26. lineNumber = true,
  27. containerWrapper = true,
  28. } = props;
  29. const codeString = useMemo(() => {
  30. const isObject: boolean = !!code && typeof code === 'object';
  31. return isObject ? JSON.stringify(code, null, 2) : code;
  32. }, [code]);
  33. return (
  34. <Highlight
  35. language={language}
  36. theme={theme}
  37. type={type}
  38. lineNumber={lineNumber}
  39. containerWrapper={containerWrapper}
  40. >
  41. {codeString}
  42. </Highlight>
  43. );
  44. }
  45. export default memo(HighlightCode);

如果 Omit 报错,tsconfig.json compilerOptions 添加

  1. "typeRoots": [
  2. "./node_modules/@types"
  3. ],

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 包大小
image.png

https://react-syntax-highlighter.github.io/react-syntax-highlighter/demo/
image.png

细节点:
需要按需加载,默认会加载所有语言,导致体积很大
image.png

prismjs代码高亮

https://prismjs.com
image.png
prism-json.js

  1. Prism.languages.json = {
  2. 'property': /"(?:\\.|[^\\"\r\n])*"(?=\s*:)/i,
  3. 'string': {
  4. pattern: /"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
  5. greedy: true
  6. },
  7. 'number': /\b0x[\dA-Fa-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?/,
  8. 'punctuation': /[{}[\]);,]/,
  9. 'operator': /:/g,
  10. 'boolean': /\b(?:true|false)\b/i,
  11. 'null': /\bnull\b/i
  12. };
  13. Prism.languages.jsonp = Prism.languages.json;

highlight.js

https://github.com/highlightjs/highlight.js
image.png
https://highlightjs.org/
image.png

BSD-3-Clause license
未经事先书面许可,不得使用著作权人或其贡献者的姓名或名称来宣传或推广由本软件衍生的产品
https://www.ruanyifeng.com/blogimg/asset/201105/bg2011050101.png

zsh-syntax-highlighting

终端命令行代码高亮
https://github.com/zsh-users/zsh-syntax-highlighting