You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

浏览器版monaco-editor右键菜单与Command Palette翻译及自定义问题咨询

Monaco Editor 浏览器版配置问题解决方案

1. 修改/完整翻译鼠标右键菜单所有选项

方案1:本地化文本替换(无需修改内置逻辑)

Monaco Editor 所有内置菜单文本都可以通过配置本地化字段覆盖,0.34.0及以上版本使用l10n配置项,旧版本使用全局MonacoEnvironment的localize方法实现:

// 0.34.0+ 版本示例
const editor = monaco.editor.create(document.getElementById('editor-container'), {
  value: 'function hello() {}',
  language: 'javascript',
  l10n: {
    // 右键菜单常见项替换示例,可根据需求添加所有需要修改的key
    'undo': '撤销',
    'redo': '重做',
    'cut': '剪切',
    'copy': '复制',
    'paste': '粘贴',
    'editor.action.formatDocument': '格式化整个文档',
    'editor.action.commentLine': '注释当前行'
  }
})

所有内置文本的key可以从Monaco Editor源码的对应本地化定义文件中查询到,直接对应替换即可。

方案2:完全自定义右键菜单

如果不需要默认的右键选项,可以直接禁用默认事件,自行实现自定义菜单:

const editor = monaco.editor.create(/* 基础配置 */)
// 拦截默认右键事件
editor.onContextMenu((event) => {
  event.preventDefault()
  // 在此处添加你的自定义菜单渲染、交互逻辑即可
})

2. 自定义命令面板(Command Palette)选项

新增自定义命令项

自定义命令需要先注册,再关联到命令面板展示:

const editor = monaco.editor.create(/* 基础配置 */)
// 第一步:注册自定义命令
editor.addCommand(
  0, // 此处可绑定快捷键,比如 monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS,不需要绑定就传0
  () => {
    // 命令触发后的执行逻辑
    console.log('执行自定义清理日志命令')
  },
  'custom.clearLogs' // 命令唯一ID
)
// 第二步:将命令注册到命令面板
monaco.editor.registerCommandPaletteAction({
  id: 'custom.clearLogs',
  label: '清理所有日志输出', // 命令面板显示的文本
  alias: '清日志', // 搜索别名,用户搜索该字符串也能匹配到该命令
  precondition: null, // 命令可执行的前置条件,无特殊要求传null
  keybindingContext: null,
  contextMenuOrder: 1
})

隐藏内置命令项

如果需要过滤命令面板中不需要的内置命令,可在初始化时添加commands.filter配置:

const editor = monaco.editor.create(document.getElementById('editor-container'), {
  // 其他基础配置
  commands: {
    filter: (commandId) => {
      // 例:隐藏内置的查找、替换命令
      const forbiddenCommands = ['editor.action.find', 'editor.action.replace']
      return !forbiddenCommands.includes(commandId)
    }
  }
})

内容的提问来源于stack exchange,提问作者Dmitrii N.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:24:03