为什么在使用 --emitDecoratorMetadata 标志编译 angular 库时会收到警告?

Why when compile angular library with --emitDecoratorMetadata flag i get warnings?

警告如

WARNING: "FormControl" and "FormBuilder" are imported from external module "@angular/forms" but never used in **\esm2015\lib\**
WARNING: "Router" is imported from external module "@angular/router" but never used in **\esm2015\lib\**
WARNING: "NgZone", "ComponentFactoryResolver", "ViewContainerRef" and "Renderer2" are imported from external module "@angular/core" but never used in **\esm2015\lib\**

关于捆绑到 FESM2015 步骤

angular 版本 12.2.13

tsconfig

{
    "compileOnSave": false,
    "compilerOptions": {
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "module": "es2020",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "importHelpers": true,
        "target": "es2017",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2020", "dom"]
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true,
        "strictInjectionParameters": true,
    }
}

tsconfig.lib.json

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "baseUrl": "./src",
        "outDir": "../../out-tsc/lib"
    },
    "files": [
        "./src/public-api.ts"
    ]
}

对于构建库使用“builder”:“@angular-devkit/build-angular:ng-packagr”,

您的 angular 图书馆应该 remove/disable emitDecoratorMetadata。 在您图书馆的 tsconfig.json 中,设置:

{
  "compilerOptions": {
    .
    .
    .
    "emitDecoratorMetadata": false
  }
}

https://github.com/angular/angular/issues/21280#issuecomment-635538723

我认为这应该没问题,并且是 Angular 12+ 的最佳路线,因为 Angular 的原理图现在实际上删除了 emitDecoratorMetadata,因为它不再需要了。 https://github.com/angular/angular-cli/commit/96a4467ce90fb6b88f5be39f73c8fd64ce057a4a https://blog.ninja-squad.com/2021/05/12/angular-cli-12.0/


另一种选择是使用单独的 import 语句将 `Type` 导入分开,但我认为从同一个库重复导入是一种不好的做法。 https://github.com/ng-packagr/ng-packagr/issues/1543#issuecomment-593873874

一个改进是使用 import type 而不是 Typescript 3.8+ 例如:

import { ChangeDetectionStrategy, Component, Input, ViewChild } from '@angular/core'
...

import type { ElementRef, NgZone, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core'
... 

https://github.com/ng-packagr/ng-packagr/issues/710#issuecomment-651139519

然而 这将因构造函数注入而失败:

Consider changing the type-only import to a regular import, or use the @Inject decorator to specify an injection token.

10   constructor(private readonly toastr: ToastrService, private readonly _location: Location) {}
                                                                          ~~~~~~~~~