Importing module from a different package in Angul

2019-02-28 08:05发布

This is a conceptual question.

I'm an absolute beginner on both Angular and npm, so this is surely a basic question, but I have been looking all over and haven't found an answer.

I want to do a little proof of concept before starting a project. I want to have a package called Imported and reuse it in a package called Importer

Importer's package.json has Imported as a dependency:

"dependencies": {
    ...
    "imported": "file:../Imported",
    ...
}

Imported is in Importer's node_modules folder, as expected.

I've followed Angular's documentation on reusing modules. The example they describe is exactly what I want, only that I want to do it from inside a dependency.

So I've imported ImportedAppModule in Importer's app.module.ts.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { ImportedAppModule } from 'imported/src/app/app.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, 
    ImportedAppModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I've also exported the component in Imported's app.module.ts :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { ImportedAppComponent } from './app.component';


@NgModule({
  declarations: [
    ImportedAppComponent
  ],
  imports: [
    BrowserModule
  ],
  exports: [
    ImportedAppComponent
  ],
  providers: [],
  bootstrap: [ImportedAppComponent]
})
export class ImportedAppModule { }

With this setup, I am getting the following error:

ERROR in ../imported/src/app/app.module.ts Module build failed: Error: \imported\src\app\app.module.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

So it seemed that I had to include this dependency in tsconfig.app.json. But I also read somewhere that I didn't have to include it there, and that I had to include it in the Importer's bootstrap array. I tried both, none of them worked, but that's fine, the configuration details are out of the scope of this question.

My question is, which one is it? What's the normal way to do this? Am I on the right track here? If so, what's the next step?

I have tried using ng build --aot in the Imported package, and added the dependency to the dist folder in Importer, but it fails and says it doesn't have a package.json, so I thought I might just try to do it jit. Still, I want to know how to do this with aot.

I would really appreciate some guidance. Thanks in advance!

1条回答
smile是对你的礼貌
2楼-- · 2019-02-28 08:25

you can use ng-packagr that Transpile your libraries to Angular Package Format
execute npm install ng-packagr --save-dev

Refer this Building an Angular 4 Component Library with the Angular CLI and ng-packagr.

查看更多
登录 后发表回答