monaco-editor的使用(antd组件中获取真实dom)

3,220 阅读1分钟

最近接到需求,需要再网页对两个文件做对比,类似于github的文档对比功能,网上查阅一番,决定使用monaco-editor(vscode真香)。但是官方的文档不太友好,再加上我的项目是umi搭建的,所以折腾一番,总算是搞定了。

最终效果图:

首先

npm install monaco-editor@0.18.1
const options = {
  enableSplitViewResizing: true,
  renderSideBySide: true,   // 对比
  language: 'javascript',   
  readOnly: true,       // 只读
  width: '100%',
  height: '100vh',
  minimap: {
    enable: false,  // 小地图
  },
};

由于我是在antd的modal里展示的,所以在componentDidMount钩子里并不能拿到DOM节点,所以在DidUpdate钩子里取。

renderEditor = () => {
    // 判断可以取到节点并且是第一次update的时候,创建编辑器
    if (document.querySelector('#container') && this.state.first) { 
        monaco.editor.createDiffEditor(document.querySelector('#container'), options).setModel({
          original: monaco.editor.createModel(this.state.oldCode),
          modified: monaco.editor.createModel(this.state.newCode),
        });
        this.setState({first: false})
    }
  };


  componentDidUpdate = () => {
    this.renderEditor();
  };

render渲染

    <Modal
          centered={true}
          width="90vw"
          style={{ overflowY: 'scroll', maxHeight: '900px' }}
          visible={showMergely}
          onCancel={() => {
            this.setState({ showMergely: false });
          }}
          onOk={() => {
            this.setState({ showMergely: false });
          }}
        >
          <div id="container" ref="container" style={{ height: '80vh' }}></div>
    </Modal>

另外语法不高亮的问题,是要配置webpack

npm install monaco-editor-webpack-plugin

import Monacoplugin from 'monaco-editor-webpack-plugin'


export default (config: Config) => {
  config.plugin('monaco-editor').use(Monacoplugin,
  {
      language: ['json', 'html', 'javascript', 'typescript']
  });
  return config;
};