如何将本地库导入您的 Angular6 应用程序?



我正在构建一个应用程序,该应用程序将使用(很可能(其他应用程序也将使用的库。在 Angular 6 中,创建新库就像ng g library MyLibrary一样简单。构建您的库,以便可以通过ng build MyLibrary在您的应用程序中使用它。最后,根据文档,您可以像导入任何其他库一样导入库,并在 app.module.ts 文件中具有import { SomethingFromMyLibrary } from 'MyLibrary';。我的问题是,为什么这对我不起作用?我收到错误Cannot find module 'AbsenceMonitorCore'对于我的情况,特定的导入语句是import { AbsenceMonitorCoreModule } from 'AbsenceMonitorCore';

这是我的库模块:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { AbsenceMonitorCoreComponent } from './absence-monitor-core.component';
import { AbsencesComponent } from './components/absences/absences.component';
import { SigninComponent } from './components/signin/signin.component';
import { LineMonitorComponent } from './components/line-monitor/line-monitor.component';
import { CurrentCalloffListComponent } from './components/current-calloff-list/current-calloff-list.component';
import { AckCalloffListComponent } from './components/ack-calloff-list/ack-calloff-list.component';
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule
],
declarations: [
AbsenceMonitorCoreComponent,
AbsencesComponent,
SigninComponent,
LineMonitorComponent,
CurrentCalloffListComponent,
AckCalloffListComponent
],
exports: [
AbsenceMonitorCoreComponent,
AbsencesComponent,
CurrentCalloffListComponent
]
})
export class AbsenceMonitorCoreModule { }

public_api.ts:

/*
* Public API Surface of absence-monitor-core
*/
export * from './lib/absence-monitor-core.service';
export * from './lib/absence-monitor-core.component';
export * from './lib/absence-monitor-core.module';

当您使用 Angular 的 CLI 创建库时,它会将 tsconfig.json 中的路径引用添加到您的库中。所以这是这样的:

{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
],
"paths": {
"AbsenceMonitorCore": [
"dist/AbsenceMonitorCore"
]
}
}
} 

经过一番尝试,我发现这是 Angular CLI 中新命令中的一个错误。当您使用ng generate library MyLibrary创建新库时,它将创建一个文件路径引用,以引用构建系统将库输出到的位置。构建系统使用的引用将存在于库的ng-package.json中。它还会在 tsconfig.json 中创建文件路径引用,以便您的应用程序可以引用您的本地库。这两个文件夹路径将有所不同。构建系统会将您的库输出到文件夹dist/my-library而您的 tsconfig.json 将具有路径dist/MyLibrary

如果您将库命名为 mylibray,则一切都会完全按照文档的描述进行。

要么更新你的tsconfig.json,你的库的ng-package.json,要么等待下一个Angular版本。

*此错误已在新版本的 CLI 中修复。