CKEditor5在线构建包在Next.js开发正常,生产环境报错求助
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包
- 进入
ckeditor5文件夹,执行npm run build重新构建 - 回到项目根目录,重新安装本地包:
npm install file:./ckeditor5
内容的提问来源于stack exchange,提问作者Anandhu Krishnan

