分享一款前端网页代码编辑器 Monaco Editor

17,211 阅读4分钟

把一个 vscode 代码编辑器引入到 vue 项目分几步?

  1. 安装 Monaco Editor
  2. 封装组件
  3. 使用组件

搞定~! 言归正传,下面我们来深入浅出的分析一下如何将 VSCode编辑器引入到 vue 前端项目。

Monaco Editor

Monaco Editor 是由 Microsoft 开发的一款基于 Web 技术的开源代码编辑器,它是 Visual Studio Code 编辑器的核心。Monaco Editor 可以嵌入到网页中,提供类似于 Visual Studio Code 的编辑体验。

官方地址: microsoft.github.io/monaco-edit…

image-20240130090727429

image-20240130092049311

优势及功能

  1. 轻量且高性能: Monaco Editor 是一款轻量级的编辑器,具有出色的性能。它专注于提供快速的代码编辑体验,适用于大型前端项目。
  2. 支持多种语言: Monaco Editor 支持多种编程语言,包括但不限于 JavaScript、TypeScript、HTML、CSS、JSON、Python 等。你可以根据项目需要切换不同的语言模式。
  3. 强大的语法高亮和代码提示: Monaco Editor 提供了高度可定制的语法高亮和代码提示功能,使得代码更易于阅读和编写。
  4. 智能代码补全: 编辑器具有智能的代码补全功能,可以根据你的输入和上下文提供准确的建议,提高编码效率。
  5. 支持多光标编辑: Monaco Editor 允许你使用多个光标进行同时编辑,从而更加灵活地进行代码重构和编辑。
  6. 集成调试支持: 在 VSCode 中内置的调试器可以与 Monaco Editor 集成,使得在编辑器中进行代码调试变得更加方便。
  7. 支持多种主题: Monaco Editor 提供了多种主题,你可以根据个人喜好选择适合你的编辑器外观。
  8. 可定制性强: Monaco Editor 具有丰富的配置选项和 API,可以根据项目需求进行高度的定制。你可以更改字体、颜色主题、键绑定等。
  9. 支持远程开发: 由于 Monaco Editor 是基于 Web 技术的,它支持远程开发,你可以在浏览器中访问代码并进行编辑,而不必在本地安装开发环境。
  10. 开源和活跃的社区: Monaco Editor 是开源项目,拥有活跃的社区支持和更新。这意味着你可以从社区中获得帮助,解决问题,并参与到项目的发展中。

安装方式

支持本地下载、npm 以及 CDN 等多种方式

npm install monaco-editor@0.45.0

在 vue 2 中封装 monaco-editor 组件

  1. 创建 MonacoEditor.vue 文件: 创建一个 Vue 组件文件,例如 MonacoEditor.vue
<!-- MonacoEditor.vue -->
<template>
  <div ref="editor" class="monaco-editor-container"></div>
</template>

<script>
// 引入 Monaco Editor
import * as monaco from 'monaco-editor';

export default {
  props: {
    // 代码内容
    code: {
      type: String,
      default: '',
    },
    // 编辑器语言
    language: {
      type: String,
      default: 'javascript',
    },
    // 编辑器主题
    theme: {
      type: String,
      default: 'vs-light', // 或 'vs-dark'
    },
  },
  data() {
    return {
      editor: null,
    };
  },
  mounted() {
    // 初始化编辑器
    this.initEditor();
  },
  watch: {
    // 监听代码内容变化
    code(newCode) {
      if (this.editor) {
        // 设置编辑器内容
        this.editor.setValue(newCode);
      }
    },
  },
  methods: {
    // 初始化编辑器
    initEditor() {
      // 创建 Monaco Editor 实例
      this.editor = monaco.editor.create(this.$refs.editor, {
        value: this.code,
        language: this.language,
        theme: this.theme,
      });

      // 监听编辑器内容变化
      this.editor.onDidChangeModelContent(() => {
        // 触发父组件更新代码内容
        this.$emit('update:code', this.editor.getValue());
      });
    },
  },
  beforeDestroy() {
    // 在组件销毁前销毁编辑器实例
    if (this.editor) {
      this.editor.dispose();
    }
  },
};
</script>

<style scoped>
.monaco-editor-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
  1. 使用组件
<template>
  <div>
    <!-- 使用封装的 MonacoEditor 组件,并传递相关属性 -->
    <MonacoEditor
      v-model="code"
      :language="language"
      :theme="theme"
    />
  </div>
</template>

<script>
// 引入 MonacoEditor 组件
import MonacoEditor from '@/components/MonacoEditor.vue'; // 请根据实际路径进行调整

export default {
  components: {
    MonacoEditor,
  },
  data() {
    return {
      // 初始化代码内容
      code: 'console.log("你好,Monaco 编辑器!");',
      // 初始化编辑器语言
      language: 'javascript',
      // 初始化编辑器主题
      theme: 'vs-light',
    };
  },
};
</script>

## 常用配置属性:

属性类型默认值说明
valuestring''设置编辑器的初始代码内容
languagestring'javascript'设置编辑器的语言模式
themestring'vs'设置编辑器的主题
fontSizenumber14设置编辑器的字体大小
readOnlybooleanfalse设置编辑器是否为只读模式

## 常用方法:

方法参数返回值说明
create(domElement, options)domElement: HTMLElement, options: IStandaloneEditorConstructionOptionsIStandaloneCodeEditor创建一个新的 Monaco Editor 实例
setValue(newValue)newValue: stringvoid设置编辑器的代码内容
getValue()-string获取编辑器的代码内容
setLayout(newLayout)newLayout: Dimensionvoid调整编辑器的布局,通常在编辑器容器大小变化时使用
setTheme(theme)theme: stringvoid设置编辑器的主题
updateOptions(newOptions)newOptions: IEditorOptionsvoid更新编辑器的选项,可以用于动态改变编辑器的配置
dispose()-void销毁编辑器实例,释放资源

更多的配置选项和 API,可以参考 Monaco Editor 的官方文档 microsoft.github.io/monaco-edit…

monaco-editor 如何隐藏右键菜单的默认项

以隐藏默认 Copy 和 Paste项为例

题库管理系统-架构图

import * as monaco from 'monaco-editor/esm/vs/editor/editor.main';
import * as actions from 'monaco-editor/esm/vs/platform/actions/common/actions';

mounted(){
  // 此处省略 初始化manaco-editor
  
  // 获取 Monaco Editor 的菜单项注册表
    let menus = actions.MenuRegistry._menuItems;

    // 查找编辑器上下文菜单的注册条目
    let contextMenuEntry = [...menus].find(entry => entry[0]._debugName == 'EditorContext');

    // 从上下文菜单的注册条目中提取菜单项
    let contextMenuLinks = contextMenuEntry[1];

    // 要移除的菜单项的命令ID列表
    let removableIds = ['editor.action.clipboardCopyAction', 'editor.action.clipboardPasteAction'];

    // 移除菜单项的函数
    let removeById = (list, ids) => {
      let node = list._first;
      do {
        // 检查当前菜单项是否应该移除
        let shouldRemove = ids.includes(node.element?.command?.id);
        if (shouldRemove) {
          // 如果应该移除,则从链表中移除当前节点
          list._remove(node);
        }
      } while ((node = node.next)); // 遍历链表
    };

    // 通过调用 removeById 函数移除特定的菜单项
    removeById(contextMenuLinks, removableIds);
}