From e266b788925421c813c1b3c6e96c6e71cea91b3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90=20Kevin=20Deng?= Date: Wed, 9 Oct 2024 19:16:47 +0800 Subject: [PATCH] refactor: javascript engine of shiki --- src/monaco/Monaco.vue | 11 +++-------- src/monaco/highlight.ts | 26 +++++++++++++++++--------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/monaco/Monaco.vue b/src/monaco/Monaco.vue index 7687f760..e67fbfb3 100644 --- a/src/monaco/Monaco.vue +++ b/src/monaco/Monaco.vue @@ -2,11 +2,9 @@ import { computed, inject, - nextTick, onBeforeUnmount, onMounted, onWatcherCleanup, - ref, shallowRef, useTemplateRef, watch, @@ -15,6 +13,7 @@ import * as monaco from 'monaco-editor-core' import { initMonaco } from './env' import { getOrCreateModel } from './utils' import { type EditorMode, injectKeyProps } from '../types' +import { registerHighlighter } from './highlight' const props = withDefaults( defineProps<{ @@ -35,7 +34,6 @@ const emit = defineEmits<{ }>() const containerRef = useTemplateRef('container') -const ready = ref(false) const editor = shallowRef() const { store, @@ -53,11 +51,8 @@ function emitChangeEvent() { emit('change', editorInstance.getValue()) } -onMounted(async () => { - const theme = await import('./highlight').then((r) => r.registerHighlighter()) - ready.value = true - await nextTick() - +onMounted(() => { + const theme = registerHighlighter() if (!containerRef.value) { throw new Error('Cannot find containerRef') } diff --git a/src/monaco/highlight.ts b/src/monaco/highlight.ts index 3c609c90..7e5391a4 100644 --- a/src/monaco/highlight.ts +++ b/src/monaco/highlight.ts @@ -1,19 +1,27 @@ import * as monaco from 'monaco-editor-core' -import { createHighlighterCore } from 'shiki/core' +import { createHighlighterCoreSync } from 'shiki/core' +import { createJavaScriptRegexEngine } from 'shiki/engine-javascript.mjs' import { shikiToMonaco } from '@shikijs/monaco' import langVue from 'shiki/langs/vue.mjs' +import langTsx from 'shiki/langs/tsx.mjs' +import langJsx from 'shiki/langs/jsx.mjs' import themeDark from 'shiki/themes/dark-plus.mjs' import themeLight from 'shiki/themes/light-plus.mjs' -export async function registerHighlighter() { - const highlighter = await createHighlighterCore({ - themes: [themeDark, themeLight], - langs: [langVue], - loadWasm: import('shiki/wasm'), - }) - monaco.languages.register({ id: 'vue' }) - shikiToMonaco(highlighter, monaco) +let registered = false +export function registerHighlighter() { + if (!registered) { + const highlighter = createHighlighterCoreSync({ + themes: [themeDark, themeLight], + langs: [langVue, langTsx, langJsx], + engine: createJavaScriptRegexEngine(), + }) + monaco.languages.register({ id: 'vue' }) + shikiToMonaco(highlighter, monaco) + registered = true + } + return { light: themeLight.name!, dark: themeDark.name!,