npm i -D monaco-editor vite-plugin-monaco-editor
安装依赖
discussions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| <script setup lang="ts">
import { onMounted, ref } from 'vue' import * as monaco from 'monaco-editor' import 'monaco-editor/esm/vs/basic-languages/css/css.contribution' import 'monaco-editor/esm/vs/basic-languages/xml/xml.contribution' import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution' //@ts-ignore import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker' //@ts-ignore
import TsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker' //@ts-ignore import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker' //@ts-ignore import CssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker' //@ts-ignore import HtmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker' // @ts-ignore self.MonacoEnvironment = { getWorker(_: string, label: string) { if (label === 'typescript' || label === 'javascript') return new TsWorker() if (label === 'json') return new JsonWorker() if (label === 'css') return new CssWorker() if (label === 'html') return new HtmlWorker() return new EditorWorker() } }
const monacoRef = ref(); const monacoInstance = ref<ReturnType<typeof monaco.editor.create>>() onMounted(() => { monacoInstance.value = monaco.editor.create(monacoRef.value,{ language:"typescript", value:"console.log('hello world')" }) }) </script> <template> <div id="monaco" ref="monacoRef"></div> </template> <style scoped> #monaco{ height: 500px; width: 500px; } </style>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' const prefix = `monaco-editor/esm/vs`; import monacoEditorPlugin from "vite-plugin-monaco-editor"
export default defineConfig({ plugins: [vue(),monacoEditorPlugin()], build:{ rollupOptions: { output: { manualChunks: { jsonWorker: [`${prefix}/language/json/json.worker`], cssWorker: [`${prefix}/language/css/css.worker`], htmlWorker: [`${prefix}/language/html/html.worker`], tsWorker: [`${prefix}/language/typescript/ts.worker`], editorWorker: [`${prefix}/editor/editor.worker`], }, }, } } })
|
运行结果:
