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

CKEditor5在线构建包在Next.js开发正常,生产环境报错求助

Next.js生产构建后CKEditor5报错:this.props.editor.create is not a function

问题场景

从CKEditor5在线构建工具下载自定义构建包,解压到项目根目录ckeditor5文件夹,执行npm add file:./ckeditor5安装本地包。开发环境运行正常,但执行npm run build + npm run export生成生产构建后,出现以下错误:

849.02b0292964587ed3.js:1 TypeError: this.props.editor.create is not a function
at ir._createEditor (849.02b0292964587ed3.js:1:27553)
at Ge._creator (849.02b0292964587ed3.js:1:27214)
at 849.02b0292964587ed3.js:1:19557
at async ir._initializeEditor (849.02b0292964587ed3.js:1:27356)
at async ir.componentDidMount (849.02b0292964587ed3.js:1:26738)
Object
phase: "initialization"
willEditorRestart: false
[[Prototype]]: Object

控制台打印editor模块内容:

Module
__esModule: true
Symbol(Symbol.toStringTag): "Module"

解决方案

1. 配置Next.js Webpack排除CKEditor5的Tree Shaking

Next.js生产构建的Tree Shaking可能误剔除了CKEditor5核心代码,在next.config.js中添加如下配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  webpack: (config) => {
    // 阻止CKEditor5本地包被tree shaking处理
    config.externals.push({
      'ckeditor5': 'commonjs ckeditor5'
    });
    return config;
  }
};

module.exports = nextConfig;

2. 确认CKEditor5的导出与导入方式

  • 检查本地ckeditor5包的主入口文件(如build/ckeditor.js)是默认导出编辑器类:
    export default class CustomEditor extends ClassicEditor {}
    
  • 在Next.js组件中使用默认导入:
    import CustomEditor from 'ckeditor5';
    // 避免使用命名导入:import { CustomEditor } from 'ckeditor5';
    

3. 用动态导入禁用SSR加载编辑器

CKEditor5依赖浏览器环境,使用next/dynamic动态导入编辑器组件并关闭SSR:

import dynamic from 'next/dynamic';

// 动态导入编辑器组件,禁用SSR
const CKEditor = dynamic(() => import('../components/CKEditor'), {
  ssr: false,
  loading: () => <p>加载编辑器中...</p>
});

// 在页面中使用
export default function EditorPage() {
  return <CKEditor />;
}

编辑器组件示例:

import { useEffect, useRef } from 'react';
import CustomEditor from 'ckeditor5';

const CKEditorComponent = ({ onChange, initialData }) => {
  const editorContainer = useRef(null);
  let editorInstance = null;

  useEffect(() => {
    const initEditor = async () => {
      editorInstance = await CustomEditor.create(editorContainer.current, {
        // 你的编辑器配置
      });
      editorInstance.setData(initialData);
      editorInstance.model.document.on('change:data', () => {
        onChange(editorInstance.getData());
      });
    };

    initEditor();

    // 组件卸载时销毁编辑器
    return () => {
      if (editorInstance) editorInstance.destroy();
    };
  }, [initialData, onChange]);

  return <div ref={editorContainer} />;
};

export default CKEditorComponent;

4. 重新构建并安装本地CKEditor5包

  1. 进入ckeditor5文件夹,执行npm run build重新构建
  2. 回到项目根目录,重新安装本地包:npm install file:./ckeditor5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:55:23