最近在实现一个数据看板的技术项目,需要将代码配置示例展示出来,并提供复制功能。
复制功能可以使用 vue-clipboard2 / vue3-clipboard 插件实现,比较简单这里不描述,主要讲讲高亮展示和格式化问题。
代码高亮
代码高亮展示可以使用 highlight.js 插件实现,仔细翻看文档可以发现官方有对 vue 专门提供一个插件 highlightjs/vue-plugin 更方便使用。

所以这边先安装这两个插件
yarn add highlight.js @highlightjs/vue-plugin
完整使用方法如下
import 'highlight.js/lib/common';
import 'highlight.js/styles/stackoverflow-light.css'; // 高亮样式
import hljsVuePlugin from '@highlightjs/vue-plugin';
const highlightjs = hljsVuePlugin.component; // 组件
<highlightjs v-if="code" :code="code"></highlightjs>
但实际上出来的效果却是所有代码都挤成一行

找原因:
1、上面传进去的 code 是代码变量通过 JSON.stringify() 转换的字符串代码,放在浏览器控制台执行一下,发现生成的就是一行代码

2、如果将已经是格式化代码的字符串传进去,就正常
const code = `[
{
"title": "apples",
"count": [12000, 20000],
"description": {"text": "...", "sensitive": false}
},
{
"title": "oranges",
"count": [17500, null],
"description": {"text": "...", "sensitive": false}
}
]`

得出结论:要展示的代码变量通过 JSON.stringify() 生成字符串后,还要再进行一次格式化,才能正常展示。
格式化代码
在线格式化代码有这个网站:beautifier.io,使用了 js-beautify 插件实现。拿来吧你~
文档描述可以格式化如下代码,够用了~
Beautify JavaScript, JSON, React.js, HTML, CSS, SCSS, and SASS
使用文档里也暴露了这三个方法:js_beautify css_beautify html_beautify

结合 highlight,具体用法如下
import 'highlight.js/lib/common';
import 'highlight.js/styles/stackoverflow-light.css';
import hljsVuePlugin from '@highlightjs/vue-plugin';
import { js_beautify } from 'js-beautify';
const highlightjs = hljsVuePlugin.component;
const codeFormat = js_beautify(props.code, {
indent_size: 2,
space_in_empty_paren: true,
});
<highlightjs v-if="code" :code="codeFormat"></highlightjs>

可以发现示例代码已经格式化高亮展示拉
上面的 js_beautify 第二个参数支持更多选项:
{
"indent_size": 4,
"indent_char": " ",
"indent_with_tabs": false,
"editorconfig": false,
"eol": "\n",
"end_with_newline": false,
"indent_level": 0,
"preserve_newlines": true,
"max_preserve_newlines": 10,
"space_in_paren": false,
"space_in_empty_paren": false,
"jslint_happy": false,
"space_after_anon_function": false,
"space_after_named_function": false,
"brace_style": "collapse",
"unindent_chained_methods": false,
"break_chained_methods": false,
"keep_array_indentation": false,
"unescape_strings": false,
"wrap_line_length": 0,
"e4x": false,
"comma_first": false,
"operator_position": "before-newline",
"indent_empty_lines": false,
"templating": ["auto"]
}
可根据需要使用,一般会设置代码缩进两个字符 indent_size: 2