webpack-angular : 包包括整个 node_modules 库

webpack-angular : bundle includes entire node_modules of library

我在文件夹 C:/libraries/someLib
中有一个本地 ng 库 我在 C:/app

下有一个应用
  1. 在应用程序中,我在依赖项下使用 file: 安装了 someLib。
  2. someLibangular@core 作为 peerDependency
  3. 应用有 angular@core 作为依赖项。

但是捆绑包中包含 libraries.
下的整个 node_modules 我错过了什么?

图片的整个左边不应该存在:

{
  "name": "someLib",
  "version": "0.0.1",
   "peerDependencies": {
     "@angular/common": "^8.1.2",
     "@angular/core": "^8.1.2"
  }

--

"dependencies": {
    "someLib": "file:../../libraries/dist/someLib",
    "@angular/core": "^8.1.2"
}

第一步需要检查您打包库的方式。 我有一个示例 github 存储库,我在 angular 库中使用了 ngx-own-carousel 并在应用程序中使用。(https://github.com/sanketmaru/ng-lib-sank)

您也可以使用此 https://blog.angularindepth.com/the-angular-library-series-publishing-ce24bb673275 教程来验证这些步骤。

您的库代码不应附带第 3 方库,每个使用库的应用程序都必须单独安装。

如果这没有帮助,您可以 post 将您的代码放在示例存储库中,我可以查看它。

本地包会发生什么,typescript 编译器会跟随 npm 创建的链接并搜索相对于库路径的库导入。

  1. Typescript 编译器读取包含 import @angular/core.
  2. 的文件 ../library/src/some.ts
  3. 它搜索相对于 library 本身的 @angular,因此 ../library/node_modules/@angular 被用作导入路径。

解决方案是在 tsconfig.json 中的 App 项目 paths 中提供,告诉编译器特定的导入应该在特定的文件夹中解析,而不管文件位于何处。

{
"compilerOptions": {      
    // Note: these paths are relative to `baseUrl` path.
    "paths": {
        "@angular/*": ["../node_modules/@angular/*"],
        "rxjs": ["../node_modules/rxjs"]
    }
},

在这种情况下,来自任何路径的任何库都将始终从应用程序的 node_modules 请求 @angular,并且只有 @angular 的一个副本将捆绑在 vendor.js.

这个在angular的文档中也有说明,但是一开始我并没有得到他们想要的。 https://github.com/angular/angular-cli/wiki/stories-linked-library#use-typesscript-path-mapping-for-peer-dependencies