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

作者:my-wl

出处:https://www.cnblogs.com/my-wl/p/17946682

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   梦羽微澜  阅读(671)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
点击右上角即可分享
微信分享提示