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

Angular中使用CKEditor触发CommonJS/AMD依赖优化警告的疑问

Angular自研库依赖CKEditor时的CommonJS警告解析

问题背景

运行自研Angular库时,持续收到构建警告:

Warning: libname.mjs depends on '@ckeditor/ckeditor5-build-classic'. CommonJS or AMD dependencies can cause optimization bailouts. For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

具体场景:

  • 自研库将@ckeditor/ckeditor5-build-classic设为peer dependency
  • 库内组件直接使用CKEditor功能
  • 宿主Angular应用已自行在package.json中安装CKEditor

目前可通过在宿主应用的angular.json中添加以下配置屏蔽警告:

"allowedCommonJsDependencies": [
    "ckeditor"
]

但存在以下疑惑:

  • 原以为CKEditor采用ECMAScript模块构建,为何会触发CommonJS警告?
  • 是否与CKEditor的tsconfig.json中设置moduleResolution: node有关?
  • 由于该库会被多个应用引用,逐个应用添加上述配置并非理想方案,需更优解。

原因解析

1. CKEditor5官方预构建包的模块格式问题

CKEditor5的官方预构建包(如@ckeditor/ckeditor5-build-classic)并非纯ES模块产物——它同时提供CommonJS和ESM两种格式,但Angular构建工具(基于Webpack)在解析时,可能优先识别到CommonJS版本。这是因为部分预构建包的package.json中,main字段指向CommonJS文件,module字段才指向ESM文件,而Angular的构建优化逻辑会针对CommonJS依赖发出警告,这类模块无法被Tree Shaking等优化手段充分处理,可能导致最终包体积增大。

2. moduleResolution: node的影响

CKEditor5的tsconfig.json中使用moduleResolution: node是Node.js标准的模块解析策略,这本身不会直接触发CommonJS警告。它仅决定CKEditor在构建时如何查找依赖文件,核心问题仍在于最终发布的包产物包含CommonJS格式。

最优解决方案

方案1:使用CKEditor5的ES模块源码自定义构建

放弃使用预构建的@ckeditor/ckeditor5-build-classic,改为直接基于CKEditor5的核心模块和插件自行构建:

  • 安装所需的核心包与插件,例如@ckeditor/ckeditor5-core、@ckeditor/ckeditor5-editor-classic、@ckeditor/ckeditor5-basic-styles等
  • 在自研库中编写CKEditor的自定义构建逻辑,确保输出纯ES模块产物
  • 这种方式既能彻底避免CommonJS依赖问题,还能按需裁剪插件,显著减小最终包体积

方案2:在自研库层面配置允许CommonJS依赖

如果必须使用预构建包,可在自研库的ng-package.json中添加配置,告知Angular构建工具将CKEditor视为允许的CommonJS依赖:

{
  "allowedCommonJsDependencies": ["@ckeditor/ckeditor5-build-classic"]
}

这样,其他应用引入该自研库时,无需再单独修改自身的angular.json配置,警告会被自动屏蔽。

方案3:强制导入CKEditor的ESM版本

检查@ckeditor/ckeditor5-build-classic的package.json,确认module字段是否存在且指向正确的ESM文件。若Angular构建工具未优先使用ESM入口,可在自研库的代码中直接导入ESM版本:

import ClassicEditor from '@ckeditor/ckeditor5-build-classic/build/ckeditor.esm.js';

通过这种方式强制使用ESM模块,可绕过构建工具对CommonJS依赖的检测。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:56:19