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

ReactJS中为Monaco Editor集成Mermaid语法报错求助

解决monaco-mermaid集成monaco-editor时的语言未识别错误

根据错误截图(错误截图),核心问题是monaco-editor无法识别'mermaid'语言,原因是代码中创建编辑器的时机早于monaco-mermaid的语言注册流程,导致语言定义未被加载。

问题代码的核心问题

你在创建编辑器实例时直接指定language: 'mermaid',但此时monaco-mermaid还未完成语言注册,monaco-editor找不到对应的语言配置,从而抛出错误。

修正方案

调整初始化顺序,先完成mermaid语言注册,再创建编辑器实例:

修正后的完整代码

import React, { useEffect, useRef } from "react";
import * as monaco from 'monaco-editor';
import initEditor from 'monaco-mermaid';
import './style.css';

const Editor = (props) => {
    const { className, handleChangeCode, handleDownload } = props;
    const editorRef = useRef(null);

    useEffect(() => {
        // 第一步:先注册mermaid语言
        initEditor(monaco);
        
        const editorContainer = document.getElementById('monaco-mermaid');
        // 第二步:创建编辑器实例
        const monacoEditor = monaco.editor.create(editorContainer, {
            language: 'mermaid',
            minimap: {
                enabled: false
            },
            fontWeight: '600',
            fontSize: '14px',
            overviewRulerLanes: 0,
            quickSuggestions: false,
        });

        // 绑定代码变化监听(确保handleChangeCode生效)
        monacoEditor.onDidChangeModelContent(() => {
            handleChangeCode?.(monacoEditor.getValue());
        });

        // 组件卸载时销毁编辑器,避免内存泄漏
        return () => {
            monacoEditor.dispose();
        };
    }, [handleChangeCode])

    return (
        <div id="editor" ref={editorRef} className="editor">
            <div className="editor-top">
                <div className="icon">Code</div>
            </div>
            <div id="monaco-mermaid" style={{height: '600px'}}></div>
            <div className={`editor-bottom`}>
                <div className="png-button" onClick={() => handleDownload('svg')}>
                    Save as SVG
                </div>
                <div className="png-button" onClick={() => handleDownload('png')}>
                    Save as PNG
                </div>
                <div className="png-button" onClick={() => handleDownload('clipboard')}>
                    Copy to clipboard
                </div>
            </div>
        </div>
    );
};

export default Editor;

额外注意事项

  • 你的版本组合(monaco-editor@0.34.0 + monaco-mermaid@1.0.8)是兼容的,无需调整版本。
  • 新增的编辑器销毁逻辑是React组件中使用monaco-editor的标准操作,避免内存泄漏。
  • 补充的代码变化监听确保handleChangeCode能实时获取编辑器内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:38:16