Monaco Editor API 使用范例

 

> [Monaco Editor](https://github.com/microsoft/monaco-editor) 是微软开发的一款开源在线代码编辑器。它是 [VSCode](https://code.visualstudio.com/) 的浏览器版本,随着近年 VSCode 大热,Monaco Editor 也逐渐走红。目前虽未登上 Online Editor 领域的宝座,却也隐燃有超越几位老前辈(指 CodeMirror, Ace 之流)之势。

 

 

GitHub项目链接:monaco-editor-demos

 

 

通过阅读本文,你可以了解以下内容:

 

1. 如何下载 Monaco Editor

2. 如何标准化搭建 Monaco Editor

3. 如何寻找相关学习资源

4. 如何调用常用 API

 

### 下载

 

新建项目文件夹,然后打开它:

 

```shell

$ mkdir my-application

$ cd my-application

```

 

接着下载 Monaco Editor:

 

```shell

$ npm install monaco-editor

```

 

### 搭建

 

本文提供了一个标准化的搭建方法,通过本文的方法搭建的 Monaco Editor 具有较强的功能扩展性。比如,如果你希望为应用添加多个编辑器,甚至文件管理系统,那么在本文提供的搭建方法之上,就可以直接添加这些新特性,从而避免不必要的踩坑。

 

本文提供两种搭建方法。

 

方法一:直接从[GitHub仓库](https://github.com/luochang212/monaco-editor-demos/tree/master/base)下载。

 

方法二:手动搭建。

 

下面说明了手动搭建的过程。

 

 

首先,在项目文件夹 `my-application` 下,新建一个名为 `base` 的文件夹。然后在该文件夹下新建 `index.html`, `app.js`, `style.css` 这三个文件:

 

```shell

$ mkdir base

$ cd base

$ touch index.html app.js style.css

```

 

在本地编辑器打开 `index.html`,输入:

 

```html

 

    Monaco Editor Demo

    

    

    

 

    基础版 Monaco Editor

    

 

```

 

打开 `app.js`,输入:

 

```js

require.config({ paths: { 'vs': '../node_modules/monaco-editor/min/vs' } });

require(['vs/editor/editor.main'], function () {

 

    // 初始化变量

    var fileCounter = 0;

    var editorArray = [];

    var defaultCode = [

        'function helloWorld() {',

        '   console.log("Hello world!");',

        '}'

    ].join('\n');

 

    // 定义编辑器主题

    monaco.editor.defineTheme('myTheme', {

        base: 'vs',

        inherit: true,

        rules: [{ background: 'EDF9FA' }],

    });

    monaco.editor.setTheme('myTheme');

 

    // 新建一个编辑器

    function newEditor(container_id, code, language) {

        var model = monaco.editor.createModel(code, language);

        var editor = monaco.editor.create(document.getElementById(container_id), {

            model: model,

        });

        editorArray.push(editor);

        return editor;

    }

 

    // 新建一个 div

    function addNewEditor(code, language) {

        var new_container = document.createElement("DIV");

        new_container.id = "container-" + fileCounter.toString(10);

        new_container.className = "container";

        document.getElementById("root").appendChild(new_container);

        newEditor(new_container.id, code, language);

        fileCounter += 1;

    }

 

    addNewEditor(defaultCode, 'javascript');

 

});

```

 

打开 `style.css`,输入:

 

```css

body {

  font-family: "Source Han Sans", "San Francisco", "PingFang SC", "Hiragino Sans GB", "Droid Sans Fallback", "Microsoft YaHei", sans-serif;

  transition: background-color .2s;

}

 

#header {

  position: fixed;

  top: 0;

  left: 0;

  height: 50px;

  right: 0;

  

  background-color: #333;

  color: #fff;

  font-size: 20px;

  

  line-height: 50px;

  display: inline-block;

  vertical-align: middle;

  padding-left: 15px;

 

  overflow: hidden;

  z-index: 0;

}

 

.container {

  position: fixed;

  top: 50px;

  left: 0;

  height: calc(100vh - 50px);

  right: 0;

 

  margin: 0 auto;

  display: block;

 

  transition: 0.2s;

  overflow: hidden;

  z-index: 0;

}

```

 

最终搭建效果如下:

 

![](/img/monaco-editor-demo-1.png)

 

### 常用 API

 

 

 

Monaco Editor 提供了极为丰富的 API,为了帮助初学者快速入门,本文提供了一些 API 调用范例。点击以下文段中的本例 Demo 链接,即可查看代码。

 

(一)获取编辑器内容

 

获取编辑器内容的 API 如下:

 

```javascript

ITextModel.getValue()

```

 

其中,`ITextModel` 是 Monaco Editor 中的一种特殊的数据类型。如果你用 `monaco.editor.create()` 函数搭建编辑器。那么 `ITextModel` 其实就是该函数的返回值。

 

Demo 效果图:

 

![](/img/monaco-editor-demo-2.png)

 

> 更多信息参见:

>

> - [本例 Demo](https://github.com/luochang212/monaco-editor-demos/tree/master/get-value)

> - [API 文档](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.istandalonecodeeditor.html#getvalue)

 

(二)实时获取光标所在行号和列号

 

获取光标所在行号和列号的 API 如下:

 

```javascript

ITextModel.getPosition().lineNumber

ITextModel.getPosition().column

```

 

如果需要实时获取,即在每次光标移动时更新行号和列号,还需要加一个监听器:

 

```javascript

ITextModel.onDidChangeCursorPosition((e) => {

    // some codes here.

});

```

 

Demo 效果图:

 

![](/img/monaco-editor-demo-3.png)

 

> 更多信息参见:

>

> - [本例 Demo](https://github.com/luochang212/monaco-editor-demos/tree/master/get-position)

> - [API 文档](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icodeeditor.html#getposition)


 

(三)语法高亮

 

设置语法高亮的 API 如下:

 

```javascript

setModelLanguage(model: ITextModel, languageId: string)

```

 

Demo 效果图:

 

![](/img/monaco-editor-demo-4.png)

 

> 更多信息参见:

>

> - [本例 Demo](https://github.com/luochang212/monaco-editor-demos/tree/master/syntax-highlight)

> - [API 文档](https://microsoft.github.io/monaco-editor/api/modules/monaco.editor.html#setmodellanguage)

 

### 学习资源

 

授人以鱼不如授人以渔,以下是几个比较重要的资料来源。Monaco Editor 的中文资源很少,因此以下都是英文资源:

 

| 链接 | 说明 |

| ----- | -----------------|

|[官方代码仓库的 issue 区](https://github.com/microsoft/monaco-editor/issues)|源代码仓库的 **issue 区**下,有很多使用者的提问。Monaco editor 的开发人员回复了其中很多问题。因此,如果你在使用中遇到麻烦,可以尝试在 issue 区用关键字搜索一下。|

|[官方代码仓库的 used by 区](https://github.com/microsoft/monaco-editor/network/dependents)|**Used by 区**的作用是寻找使用了本框架的其他开源仓库。如果有毅力一直翻下去,你很可能会找到和你用该框架做相似实现的仓库。那么你就可以借鉴他的代码了。|

|[官方 demo 仓库](https://github.com/microsoft/monaco-editor-samples)|**官方 demo 仓库**是个好东西,这是一切开始的地方。跑一跑官方demo,很多事就不言自明了,省了翻阅文档的时间。|

|[Playground](https://microsoft.github.io/monaco-editor/playground.html)|**Playground** 和 官方 demo 仓库作用差不多,但它是部署在网络上的。可以先在 playground 里试验以后,明确自己需要这个功能了,然后再在本地搭建。|

|[API 文档](https://microsoft.github.io/monaco-editor/api/)|鉴于 Monaco Editor 是一个仍在更新的项目,**API 文档** 的内容也未必完全正确。但它确实是收录 API 最全面的地方。如果你需要实现的功能比较偏门,找不到任何 demo 和教程,那么自己查 API 文档往往是最终的办法。|

|[Stackoverflow](https://stackoverflow.com/questions/tagged/monaco-editor)|**Stackoverflow** 也有很多关于 Monaco Editor 的问答。|

 

 

### 推荐阅读

 

如果你对本项目感兴趣,那么你可能同样对 [Monaco Speech Editor](https://luochang212.github.io/gadget/monaco-speech-editor/) 感兴趣。

 

> **Note:** Monaco Speech Editor 是笔者编写的一款适用于视障人群的在线代码编辑器。它提供丰富的语音辅助功能,可以精准地定位并朗读用户指定内容。并且,它还提供多种语音模式,比如字符模式、音乐模式、全局模式。这些模式可以根据用户在不同编程阶段的不同需求,提供差异化的语音内容输出。此外,它内置供全盲者使用的操作界面,从而使全盲者无需使用电脑屏幕和鼠标,也能正常使用本编辑器。

 

Monaco Speech Editor 中集成了大量 Monaco Editor 的 API。并且在细节上做了很多优化。[本项目](https://github.com/luochang212/monaco-editor-demos)是 Monaco Speech Editor 的子项目,是把 Monaco Speech Editor 中可以通用的部分代码抽取出来形成的。如果想尝试 Monaco Editor 的更多功能,欢迎 star, clone 和 fork。

你可能感兴趣的:(JavaScript,Monaco,editor,API,教程,编辑器,开源)