感谢大佬的解决方案,这里可以直接参考以上链接的issue。
有三种解决方案:
1. 使用对应版本
"monaco-editor": "^0.38.0",
"vite": "^3.0.2",
"vite-plugin-monaco-editor": "^1.1.0",
2. 自己手动创建一个lib,例如monco.ts, 之后导入的时候直接使用 import {monco} from "@/lib/monco"即可(注:和正常使用是一样的)。
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
import 'monaco-editor/esm/vs/basic-languages/markdown/markdown.contribution';
import 'monaco-editor/esm/vs/editor/editor.all.js';
import 'monaco-editor/esm/vs/language/typescript/monaco.contribution';
import 'monaco-editor/esm/vs/language/json/monaco.contribution';
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';
// @ts-ignore
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();
},
};
export { monaco };
3. 使用插件(以下方式我出现错误:monacoEditorPlugin not a function,删掉package中的type = module正常。你们可以自己试试。)
import monacoEditorPlugin from 'vite-plugin-monaco-editor';
export default defineConfig({
build: {
lib: {
....
},
},
plugins: [
monacoEditorPlugin({
languageWorkers: ['editorWorkerService', 'json', 'typescript'],
}),
...