CKEditor5 中 CKEDITOR 未定义问题的完整解决方案

ckeditor5 已彻底弃用全局 `ckeditor` 对象(如 `ckeditor.replace()`),改用基于 es 模块的 `classiceditor.create()` 等现代 api;配置需通过 `htmlsupport`、`toolbar` 等选项对象传入,而非旧版全局方法。

CKEditor5 是 CKEditor 的全新架构版本,完全重写为模块化、面向现代 Web 标准的编辑器,与经典的 CKEditor4 在 API 设计上存在根本性差异。你遇到的 Uncaught ReferenceError: CKEDITOR is not defined 错误,正是由于错误地沿用了 CKEditor4 的全局 API(如 CKEDITOR.replace())——该 API 在 CKEditor5 中已被彻底移除,不再存在。

在你的代码中,以下两段逻辑存在冲突:


✅ 正确配置方式:使用 htmlSupport 启用自定义 HTML

若目标是允许

ClassicEditor
    .create(document.querySelector('#editor'), {
        htmlSupport: {
            allow: [
                {
                    name: /.*/,      // 匹配所有 HTML 标签名(包括 style)
                    attributes: true, // 允许所有属性(如 id、rel)
                    classes: true,    // 允许所有 class 名
                    styles: true      // 允许所有内联 CSS(如 style="color:red")
                }
            ]
        }
    })
    .then(editor => {
        console.log('Editor initialized:', editor);
        window.editor = editor; // 可选:挂载到全局便于调试
    })
    .catch(error => {
        console.error('Editor initialization failed:', error);
    });
⚠️ 注意事项:htmlSupport 是白名单机制,上述正则 /.*/ 表示“允许全部”,生产环境建议显式声明所需标签(如 name: /^(div|span|style|p|a)$/),以提升安全性;若需支持 或 on* 事件属性,需额外配置 allow 中的 attributes: { patterns: /./ } 并启用 dangerousHTML —— 但强烈不推荐,存在 XSS 风险;CKEditor5 默认会过滤掉 style 标签和非白名单属性,因此必须显式启用 htmlSupport,否则即使 DOM 中存在也不会渲染。

? 对比总结:CKEditor4 → CKEditor5 迁移关键点

功能 CKEditor4(已弃用) CKEditor5(当前标准)
初始化方式 CKEDITOR.replace('id') ClassicEditor.create(element, config)
全局对象 CKEDITOR(存在) ❌ 不存在
自定义 HTML 支持 extraAllowedContent htmlSupport.allow[] + 正则/对象规则
配置传递位置 全局变量或 replace() 参数 create() 的第二个参数(纯对象)

只要摒弃 CKEditor4 的思维惯性,严格遵循 CKEditor5 的模块化配置范式,即可避免此类引用错误,并获得更安全、可维护的富文本编辑体验。