create-react-app react中使用monaco-editor v0.44

在通过create-react-app创建的react应用中使用monaco-editor v0.44

下载包:

npm i monaco-editor
npm i monaco-editor-webpack-plugin

安装插件:
使用craco自定义webpack配置

npm i craco

package.json

"scripts": {
   "start": "craco start",
   "build": "craco build",
},

在项目根目录创建craco.config.js文件,文件内容:

const path = require('path')
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
  webpack: {
    // 别名配置
    alias: {
      '@': path.resolve(__dirname, 'src')
    },
    // 插件
    configure(webpackConfig) {
      webpackConfig.plugins.push(new MonacoWebpackPlugin())
      return webpackConfig
    }
  }
}

不配置插件会报错或者代码不高亮,没有提示等问题:
image

Error: Unexpected usage
    at EditorSimpleWorker.loadForeignModule

在组件中使用

import * as monaco from 'monaco-editor'

interface MonacoEditorProps {
  code?: string
  language: 'javascript' | 'json'
  disabled?: boolean
}

// 省略部分无关代码
const MonacoEditor: FC<MonacoEditorProps> = (props) => {
  const editContainerRef = useRef(null)
  const editor = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);

  useEffect(() => {
    if(editContainerRef.current && !editor.current) {
      editor.current = monaco.editor.create(editContainerRef.current, {
        value: '',
        language: props.language,
        minimap: {
          enabled: false
        },
        colorDecorators: true, // 颜色装饰器
        automaticLayout: true,
        theme: 'vs-black',
        glyphMargin: true,
      })
    }

    window.addEventListener("resize", function () {
      editor.current?.layout()
    });

    return () => {
      window.removeEventListener("resize", function () {
        editor.current?.layout()
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div className="react-monaco-editor" style={{ width: '100%', height: '100%' }}>
      <div ref={editContainerRef} style={{ width: '100%', height: '100%' }}></div>
    </div>
  )
}

就可以正常使用了
image

posted @ 2024-01-05 09:56  梦羽微澜  阅读(594)  评论(1编辑  收藏  举报