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

如何在Angular库中导入自定义构建的CKEditor5文件?

Angular库中自定义CKEditor5构建文件导入失败的解决方案

问题描述

在开发名为core-lib的Angular库时,rich-text-editor组件作为自定义CKEditor5的包装组件,通过相对路径导入模块内assets文件夹中的构建文件:

import * as ClassicEditor from '../../assets/js/ckeditor5/build/ckeditor';

但执行库构建时出现错误:

× Generating FESM2020
ERROR: Could not resolve "../../assets/js/ckeditor5/build/ckeditor" from "dist/core-lib/esm2020/rich-text/components/rich-text-editor/rich-text-editor.component.mjs"

问题根源

Angular库构建工具ng-packagr默认不会自动将模块内部assets目录的文件复制到dist输出目录;同时构建后组件文件的目录结构发生变化,原相对路径无法匹配到资源文件的实际位置。

解决步骤

1. 配置ng-packagr打包资源

在core-lib库的ng-package.json文件中添加assets配置,指定要打包的CKEditor资源路径:

{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../dist/core-lib",
  "lib": {
    "entryFile": "src/public-api.ts"
  },
  "assets": [
    {
      "input": "src/lib/rich-text/assets/js/ckeditor5",
      "output": "assets/js/ckeditor5"
    }
  ]
}

该配置会将模块内的CKEditor构建文件复制到dist/core-lib/assets/js/ckeditor5目录下。

2. 修正组件导入路径

构建后组件文件位于dist/core-lib/esm2020/rich-text/components/rich-text-editor/,资源文件在dist/core-lib/assets/,调整导入路径为:

import * as ClassicEditor from '../../../../../assets/js/ckeditor5/build/ckeditor';

若想避免层级变化导致的路径问题,可使用动态导入结合APP_BASE_HREF:

import { APP_BASE_HREF } from '@angular/common';
import { Inject } from '@angular/core';

export class RichTextEditorComponent implements ControlValueAccessor {
  public Editor: any;

  constructor(@Inject(APP_BASE_HREF) private baseHref: string) {
    const ckeditorPath = `${this.baseHref}assets/js/ckeditor5/build/ckeditor.js`;
    import(ckeditorPath).then(module => {
      this.Editor = module.default;
    });
  }
}

3. 更规范的替代方案

将自定义构建的CKEditor发布为私有npm包,在core-lib的package.json中添加依赖:

npm install ./path/to/your-custom-ckeditor-build

之后直接通过包名导入:

import * as ClassicEditor from 'your-custom-ckeditor-build';

验证构建

重新执行库构建命令:

ng build core-lib

检查dist/core-lib/assets/js/ckeditor5目录是否存在,且组件导入路径能正确匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:39:52