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

如何将未发布至npm的ng-packagr打包Angular库作为Git依赖引入?

解决Git托管的Angular库(未发npm)作为项目依赖的问题

别担心,完全可以搞定!你不需要把库发布到npm或者私有仓库,就能直接把Git仓库里的Angular库作为依赖引入到另一个项目里。我给你拆解一下具体步骤:

1. 先配置你的Angular库项目

首先确保你的库项目里的配置是正确的:

  • 在库的根目录package.json中,把main、module、typings这些字段指向dist文件夹里的对应产物,这样npm和Angular才能找到正确的入口文件。比如:
{
  "name": "your-custom-library",
  "version": "1.0.0",
  "main": "./dist/your-custom-library/bundles/your-custom-library.umd.js",
  "module": "./dist/your-custom-library/fesm2020/your-custom-library.mjs",
  "typings": "./dist/your-custom-library/your-custom-library.d.ts",
  "scripts": {
    "build": "ng-packagr -p ng-package.json"
  }
}
  • 确认ng-package.json的配置正确,输出目录是dist(默认就是这个,一般不用改)。

2. 在目标项目中添加Git依赖并配置自动构建

在你要引入库的目标项目里,修改package.json:

  • 在dependencies里添加你的Git仓库地址,格式可以是SSH或者HTTPS的,比如:
"dependencies": {
  "your-custom-library": "git+ssh://git@your-git-server.com/your-username/your-custom-library.git#main"
}

这里的#main是指定仓库的分支,你可以换成你需要的分支名或者commit哈希。

  • 添加postinstall脚本,让npm在安装依赖后自动构建库的dist文件夹:
"scripts": {
  "postinstall": "cd node_modules/your-custom-library && npm install && npm run build"
}

这个脚本会在npm install完成后,自动进入库的目录,安装库的依赖,然后执行构建命令生成dist产物。

3. 配置TypeScript路径解析(可选但推荐)

如果遇到TypeScript无法正确解析库导入路径的问题,可以在目标项目的tsconfig.json里添加paths配置:

{
  "compilerOptions": {
    // 其他配置...
    "paths": {
      "your-custom-library": [
        "node_modules/your-custom-library/dist/your-custom-library"
      ],
      "your-custom-library/*": [
        "node_modules/your-custom-library/dist/your-custom-library/*"
      ]
    }
  }
}

这样就能确保TypeScript能找到库的类型定义和模块文件。

额外小提示

  • 如果不想每次npm install都重新构建库,可以考虑把dist文件夹也提交到Git仓库里(虽然这不是最优雅的做法,但能省掉构建时间)。
  • 把库的依赖设为peerDependencies,这样目标项目会复用自己的Angular等依赖版本,避免重复安装和版本冲突。比如在库的package.json里:
"peerDependencies": {
  "@angular/common": "^16.0.0",
  "@angular/core": "^16.0.0"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:05:52