我正在构建一个应用程序,该应用程序将使用(很可能)其他应用程序也会使用的库。在 Angular 6 中,创建一个新库就像ng g library MyLibrary. 构建您的库,使其可在您的应用程序中使用ng build MyLibrary。最后,根据文档,您可以像import { SomethingFromMyLibrary } from 'MyLibrary';在 app.module.ts 文件中导入任何其他库一样导入您的库。我的问题是,为什么这对我不起作用?我收到错误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 中修复。
| 归档时间: | 
 | 
| 查看次数: | 9245 次 | 
| 最近记录: |