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

如何构建Angular公共库实现按模块路径导入以避免命名冲突

实现Angular私有库的分路径导入

要实现你想要的分模块导入结构,按以下步骤操作即可:

1. 调整库的目录结构

把不同组的函数、类拆分到独立的子目录中,每个子目录单独维护导出入口:

common-library/
├── src/
│   ├── lib/
│   │   ├── functionset1/
│   │   │   ├── func1.ts       // 存放functionset1下的func1
│   │   │   └── index.ts       // 子模块导出入口
│   │   ├── functionset2/
│   │   │   ├── func1.ts       // 存放functionset2下的func1
│   │   │   └── index.ts
│   │   └── public-api.ts      // 库的根导出文件

每个子目录的index.ts负责导出当前模块的所有内容,例如functionset1/index.ts:

export { func1 } from './func1';
// 若有同模块的其他函数/类,一并在此导出

2. 配置根导出文件public-api.ts

在库的根public-api.ts中,导出所有子模块的内容,确保构建工具能识别这些子模块:

export * from './lib/functionset1';
export * from './lib/functionset2';

3. 修改库的package.json添加路径映射

在库的package.json中新增exports字段,明确每个子路径对应的打包后文件位置,让Node和Angular构建工具能正确解析导入路径:

{
  "name": "common-library",
  "exports": {
    ".": "./dist/common-library/public-api.js",
    "./functionset1": "./dist/common-library/lib/functionset1/index.js",
    "./functionset2": "./dist/common-library/lib/functionset2/index.js"
  },
  // 保留原有其他配置(版本、scripts等)
}

注意路径要和Angular CLI默认构建后的dist目录结构对应,若你的构建配置有修改,需同步调整这里的路径。

4. 构建库并测试导入

执行库的构建命令:

ng build common-library

之后在目标Angular项目中,就可以按预期方式导入:

// 导入不同模块的同名函数
import { func1 } from 'common-library/functionset1';
import { func1 } from 'common-library/functionset2';

// 类的导入同理,比如拆分后的Item类
import { Item } from 'common-library/item-module';

如果是本地私有库,记得在目标项目的package.json中关联这个库,比如用本地文件路径:

{
  "dependencies": {
    "common-library": "file:../path/to/common-library"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:07:09