之前,vue3+webpack使用monaco-editor以及script引入monaco-editor,都没有问题,这次又在vue3+vite上使用到了monaco-editor。
vite没有对应的monaco-editor-webpack-plugin
插件,所以,如果直接使用并初始化,可以看到效果,但是会报错:
Error: Unexpected usage at EditorSimpleWorker.loadForeignModule
按照下面方法即可:
// 除了引入编辑器,还需要引入相关的worker: import * as monaco from 'monaco-editor' import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker' import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker' import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker' import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker' import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker' // 在初始化之前,先设置MonacoEnvironment self.MonacoEnvironment = { getWorker(_, label) { if (label === 'json') { return new jsonWorker() } if (label === 'css' || label === 'scss' || label === 'less') { return new cssWorker() } if (label === 'html' || label === 'handlebars' || label === 'razor') { return new htmlWorker() } if (label === 'typescript' || label === 'javascript') { return new tsWorker() } return new editorWorker() } } // 再初始化,问题就解决了 const editor = monaco.editor.create(document.getElementById('codeEditBox'), { value: this.modelValue, // 编辑器初始显示文字 language: this.language, theme: 'vs', // 官方自带三种主题,vs,hc-black,vs-dark selectOnLineNumbers: true, // 显示行号 roundedSelection: false, readOnly: false, // 只读 cursorStyle: 'line', // 光标样式 automaticLayout: true, //自动布局 glyphMargin: true, //字形边缘 useTabStops: false, fontSize: 15, //字体大小 autoIndent: true, //自动布局 quickSuggestionsDelay: 100, //代码提示延时 })