【问题标题】:NPM package is not imported in angular production appNPM 包未在 Angular 生产应用程序中导入
【发布时间】:2019-03-29 19:05:06
【问题描述】:

目标

我正在尝试将 rxjs 的 typescript 模块增强作为 npm 包提供给 Angular 项目。

问题

在 Angular 应用程序中使用包在本地开发模式下可以正常工作,但是一旦为生产构建了应用程序,包就不会被导入到最终的 dist 中。

详情

  • 大部分增强是提供一种新方法:Observable.safeSubscribe()
    (完整源代码:ngx-safe-subscribe.ts

    import { Observable, Subscription } from 'rxjs';
    
    declare module 'rxjs/internal/Observable' {
        interface Observable<T> {
            safeSubscribe: typeof safeSubscribe;
        }
    }
    
    export function safeSubscribe<T>(...): Subscription {
        ...
    }
    Observable.prototype.safeSubscribe = safeSubscribe;
    
  • 包是用ng-packagr构建的

  • 在 Angular 项目中导入并使用后,一切正常:
    (在此处完成演示:demo

    import { Component, OnDestroy } from '@angular/core';
    import { of } from 'rxjs';
    import '@badisi/ngx-safe-subscribe';
    
    @Component({
        selector: 'my-app',
        templateUrl: './app.component.html'
    })
    export class AppComponent implements OnDestroy  {
        constructor() {
            of([]).safeSubscribe(this, () => { console.log('ok'); });
        }
        ngOnDestroy(): void {}
    }
    
  • 一旦为生产而构建,包就不会导入到最终的 dist 中:

    ng serve --prod
    
    [error in console]: TypeError: Object(...)(...).safeSubscribe is not a function
    
  • 我最后的尝试是用最新的东西进行的

    angular@7.0.0, typescript@3.1.3, ng-packagr@4.4.0
    
  • 附带说明,在 Visual Studio Code 中使用命名的导入样式会产生以下结果:

    import { safeSubscribe } from '@badisi/ngx-safe-subscribe';
    
    [ts] 'safeSubscribe' is declared but its value is never read. 
    

很难判断问题是否来自 typescript、angular-cli、webpack 甚至 ng-packagr 无法识别扩充并将其正确导入最终 dist。

因此,我们将非常感谢您的帮助!
谢谢。

【问题讨论】:

    标签: typescript npm webpack angular-cli ng-packagr


    【解决方案1】:

    您是在尝试 ng serve --prod 还是 ng build --prod?

    【讨论】:

    • 两者都导致了同样的问题。我刚刚回答了我自己的问题,但感谢您的帮助!
    【解决方案2】:

    自己找到了答案,但并非没有困难..

    快速解答

    将以下属性添加到 npm 包中:

    package.json {
        sideEffects: true
    } 
    

    说明

    问题与 ng-packagr 有关,它在 package.json 文件的 dist 版本中设置了 sideEffects:false。 p>

    这是 Angular Package Format v6 推荐的设置以优化分发包:

    "包含此属性设置为 false 的包将由 webpack 比那些没有的更积极。的最终结果 这些优化应该是更小的包大小和更好的代码 代码拆分后以捆绑块的形式分发" [source]

    当设置为 false 时,只会捆绑实际使用的代码部分。但是,在我的情况下,增强被识别为“已声明但从未读取”,因此在构建过程中被忽略。将 sideEffects 设置为 true,webpack 将毫无疑问地简单地捆绑整个包。

    【讨论】:

      猜你喜欢
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 2019-11-29
      • 2017-12-24
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多