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

使用react-monaco-editor时如何在同一页面配置两种不同字体?

解决方案
  • 第一步:强制覆盖Monaco编辑器容器的字体样式,避免测量元素继承全局字体配置。在全局CSS中添加如下规则,确保优先级高于你之前设置的全局字体系列规则,避免被覆盖:
.monaco-editor,
.monaco-editor .inputarea.ime-input,
.monaco-editor .margin-view-overlays,
.monaco-editor .lines-content {
  font-family: "Fira Code", monospace !important;
}
  • 第二步:调整remeasureFonts的调用时机,确保在字体加载完成、编辑器实例完全挂载后再执行。渲染前或Hook初始化早期调用时,字体未加载完成、编辑器实例还未生成,调用不会生效。React组件中的示例代码如下:
import React, { useEffect, useRef } from 'react';
import MonacoEditor from 'react-monaco-editor';

const CodeEditor = () => {
  const editorRef = useRef(null);
  const monacoRef = useRef(null);

  const handleEditorMount = (editor, monaco) => {
    editorRef.current = editor;
    monacoRef.current = monaco;
  };

  useEffect(() => {
    if (!editorRef.current || !monacoRef.current) return;
    // 等待所有字体加载完成后再触发重测量
    document.fonts.ready.then(() => {
      monacoRef.current.editor.remeasureFonts();
      // 可选:如果仍然有偏移,可以手动触发一次编辑器布局重计算
      editorRef.current.layout();
    });
  }, [editorRef.current, monacoRef.current]);

  return (
    <MonacoEditor
      language="javascript"
      theme="vs-dark"
      options={{
        fontFamily: '"Fira Code", monospace',
        renderWhitespace: "all",
        // 其他原有配置项
      }}
      onMount={handleEditorMount}
    />
  );
};

export default CodeEditor;
  • 第三步:如果上述操作后仍存在测量偏差,可在编辑器配置项中添加disableMonospaceOptimizations: true,关闭Monaco针对等宽字体的默认优化逻辑,适配自定义字体的测量规则。

内容的提问来源于stack exchange,提问作者zhshch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:36:04