代码高亮
小于 1 分钟
代码高亮
提示
代码高亮可以使用highlight.js或者prismjs
可以使用highlight.js自己封装组件
import { ref, h, computed, defineComponent, Plugin, watch } from "vue";
import hljs from "highlight.js/lib/core";
import "highlight.js/styles/atom-one-dark.css";
export function escapeHtml(value: string): string {
return value
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const Highlight = defineComponent({
props: {
code: {
type: String,
required: true,
},
language: {
type: String,
default: "",
},
autodetect: {
type: Boolean,
default: true,
},
ignoreIllegals: {
type: Boolean,
default: true,
},
},
setup(props) {
const language = ref(props.language);
watch(
() => props.language,
(newLanguage) => {
language.value = newLanguage;
}
);
const autodetect = computed(() => props.autodetect || !language.value);
const cannotDetectLanguage = computed(
() => !autodetect.value && !hljs.getLanguage(language.value)
);
const className = computed((): string => {
if (cannotDetectLanguage.value) {
return "";
} else {
return `hljs ${language.value}`;
}
});
const highlightedCode = computed((): string => {
// No idea what language to use, return raw code
if (cannotDetectLanguage.value) {
console.warn(
`The language "${language.value}" you specified could not be found.`
);
return escapeHtml(props.code);
}
if (autodetect.value) {
const result = hljs.highlightAuto(props.code);
language.value = result.language ?? "";
return result.value;
} else {
const result = hljs.highlight(props.code, {
language: language.value,
ignoreIllegals: props.ignoreIllegals,
});
return result.value;
}
});
return {
className,
highlightedCode,
};
},
render() {
return h("pre", {}, [
h("code", {
class: this.className,
innerHTML: this.highlightedCode,
}),
]);
},
});
// const plugin: Plugin & { component: typeof component } = {
// install(app) {
// app.component("highlightjs", component);
// },
// component,
// };
// export default plugin;
export default Highlight;
如何使用
<div id="app">
<!-- bind to a data property named `code` -->
<highlight autodetect :code="code" />
<!-- or literal code works as well -->
<highlight language='javascript' code="let x = 5;" />
</div>
prismjs
示例
<!DOCTYPE html>
<html>
<head>
...
<link
href="https://unpkg.com/prismjs@1.27.0/themes/prism-tomorrow.min.css"
rel="stylesheet"
/>
</head>
<body>
<div>
<pre>
<code class="language-javascript line-numbers">
import { h, ref } from 'vue'
const RedDiv = (_, ctx) => h(
'div',
{
class: 'red-div',
},
ctx.slots.default()
)
const msg = 'Markdown 中的 Vue'
const count = ref(0)
</code>
</pre>
</div>
<script src="https://unpkg.com/prismjs@1.27.0/components/prism-core.js"></script>
<script src="https://unpkg.com/prismjs@1.27.0/plugins/autoloader/prism-autoloader.min.js"></script>
</body>
</html>