Angular引入CKEditor5自定义构建报create属性缺失错误
报错现象
Angular项目集成CKEditor5自定义构建版本时,TS抛出类型错误:Property 'create' is missing in type '{ CKSource: {}; }' but required in type 'EditorConstructor'
对应报错截图:
这个错误是TypeScript类型校验触发的,代表传给<ckeditor>组件的editor入参不是合法的编辑器构造函数:传入值缺少编辑器类必须的静态create方法,被TS识别成了普通对象。
绝大多数场景由两类问题触发:
- 组件内给editor属性赋值时多套了一层对象结构,没有直接传入编辑器构造函数
- 自定义构建的CKEditor包没有正确导出构造类,或者TS缺少对应类型声明,把导入的构造函数推导成了普通对象
按优先级依次排查处理:
修正组件内的赋值写法
最常见的踩坑是赋值时刻意包裹了带CKSource字段的多余对象,错误写法示例:// 错误写法,会直接触发当前报错 public Editor = { CKSource: MyCustomEditor }改成直接赋值导入的自定义编辑器构造函数即可:
// 先导入你的自定义构建产物,路径替换为本地实际构建文件路径 import MyCustomEditor from 'src/assets/ckeditor/ckeditor'; // 直接赋值构造函数,不要套额外对象层 public Editor = MyCustomEditor;模板侧正常绑定属性即可,不需要额外调整:
<ckeditor [editor]="Editor" [data]="editorContent"></ckeditor>注意:赋值时必须直接传入编辑器构造函数本身,任何额外的对象包裹都会触发当前类型报错。
补全类型声明绕过TS校验
如果写法确认没问题,是TS无法识别自定义构建包的类型导致的推导错误,在项目src目录下新建ckeditor-custom-typings.d.ts文件,添加如下声明:declare module 'src/assets/ckeditor/ckeditor' { const EditorConstructor: { create(target: any, config?: Record<string, any>): Promise<any>; [prop: string]: any; }; export default EditorConstructor; }不想额外写类型声明的话,也可以直接用类型断言快速修复:
public Editor = MyCustomEditor as any;修复自定义CKEditor构建的导出逻辑
如果以上两步都没解决,检查自行打包的CKEditor自定义构建入口,确保导出的是继承了基础编辑器类的构造函数,而不是实例对象,正确的入口写法参考:import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor'; import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials'; import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold'; import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic'; // 其他需要集成的插件依次导入 export default class MyCustomEditor extends ClassicEditor {} // 注册内置插件 MyCustomEditor.builtinPlugins = [ Essentials, Bold, Italic ]; // 编辑器默认配置 MyCustomEditor.defaultConfig = { toolbar: { items: ['bold', 'italic'] } };修改完入口后重新打包自定义构建,替换Angular项目里引用的构建文件即可。
内容的提问来源于stack exchange,提问作者Deepak Kumar

