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

本文介绍了如何在使用create-react-app构建的React应用中集成MonacoEditor,包括安装、配置Webpack和craco,以及在组件中正确导入和使用MonacoEditor以实现代码高亮和编辑功能。
摘要由CSDN通过智能技术生成

在使用通过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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值