Monaco Editor 快速入门

2,471 阅读1分钟

前段时间的中后台项目里经常有代码编辑器的需求,多次使用到了Monaco Editor,这里做个简单的梳理;

安装

使用编辑器时,同时需要配合对应的webpack插件使用,因此首先npm进行安装;

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

webpack配置

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports={
    ...
  // 在webpack的配置文件中增加如下plugins的配置
  plugins: [
    new MonacoWebpackPlugin(['csharp', 'java', 'javascript', 'typescript', 'json']),
  ],
}

编写一个组件

接着,我们可以开始写一个组件来展示编辑器内容了,具体如下:

import React, { useEffect } from "react";
import * as monaco from "monaco-editor";
export default function Editor({id,height,children}) {
  // id:id名称,height:编辑器高度 ,children:子节点
  useEffect(() => {
    createEditor();
  }, []);
  const createEditor = () => {
    monaco.editor.create(document.getElementById(id), {
      readOnly: true,
      value: children,
      language: "html",
      lineNumbers: "off",
      scrollBeyondLastLine: false,
    });
  };
  return (
    <div
      id={id}
      style={{
        height,
        width: "100%",
        border: "1px solid #f0f0f0",
        overflow: "hidden",
        margin: "5px 0",
      }}
    ></div>
  );
}

使用组件

接下来就可以到处使用它了

import React from "react";
import Editor from "./Editor.jsx";
export default function Help(props) {
  return (
    <div style={{ padding: "30px" }}>
      <Editor height="300px" id="xml-top">
        {`
<sitemapindex>
  <sitemap>
    <loc>
      http://www.abc.com/structure/index_1.xml
    </loc>
    <lastmod>2013-12-18 12:59:12</lastmod>
  </sitemap>
  <sitemap>
    <loc>
      http://www.abc.com/structure/index_2.xml=
    </loc>
    <lastmod>2013-12-18 12:59:13</lastmod>
  </sitemap>
</sitemapindex>`}
      </Editor>
    </div>
  );
}

效果图

alt

相关文档