推荐使用 @monaco-editor/react,基于 react 封装

对于企业级应用来说,依赖三方 cdn 是个潜在的风险点,
私有化部署需求,把 paths.vs 配本地,同时用 copy-webpack-plugin 复制 monaco-editor 相应代码到产物目录

  1. import React, { useRef } from 'react';
  2. import Editor, { loader } from '@monaco-editor/react';
  3. const loaderConfig = {
  4. 'vs/nls': {
  5. availableLanguages: {
  6. '*': 'zh-cn',
  7. },
  8. },
  9. paths: {
  10. // 根据需要调整版本和产物类型
  11. // https://cdn.jsdelivr.net/npm/monaco-editor@0.43.0/min/vs
  12. vs: 'https://gw.alipayobjects.com/os/lib/monaco-editor/0.34.0/min/vs',
  13. },
  14. };
  15. loader.config(loaderConfig);
  16. function MonacoEditor () {
  17. const editorRef = useRef(null);
  18. function onEditorDidMount(editor, monaco) {
  19. console.log('editor', editor, monaco)
  20. editorRef.current = editor;
  21. }
  22. function onEditorChange(value, event) {
  23. console.log('here is the current model value:', value);
  24. }
  25. return (
  26. <Editor
  27. height={600}
  28. language="javascript"
  29. theme="vs-dark"
  30. defaultValue="console.log('hello world')"
  31. onMount={onEditorDidMount}
  32. onChange={onEditorChange}
  33. />
  34. )
  35. }
  36. export default MonacoEditor;

如果不用 cdn 的私有化部署需求,可以把 paths.vs 配本地,将资源放置本地,替换cdn资源
同时用 copy-webpack-plugin 复制 monaco-editor 相应代码到产物目录

loader

https://github.com/suren-atoyan/monaco-loader
用vs 作为路径别名,避免路径过长的问题

vs 默认配置
https://github.com/suren-atoyan/monaco-loader/blob/master/src/config/index.js

loader.init

  1. loader.init().then((monaco) => {
  2. const wrapper = document.getElementById("root");
  3. wrapper.style.height = "100vh";
  4. const properties = {
  5. value: "function hello() {\n\talert('Hello world!');\n}",
  6. language: "javascript"
  7. };
  8. monaco.editor.create(wrapper, properties);
  9. });