Friedrich
Friedrich

Reputation: 1402

How can I import a feature module from an custom Angular library?

Similar to this question I built a custom Angular library (with Angular CLI 7.2.0) with multiple feature modules:

MyLibraryModule
  FeatureModule1
    SomeComponent1
  FeatureModule2
    SomeComponent2

I want to import only one feature module into my main application, like we can do with Angular Material modules (import { MatButtonModule } from '@angular/material';):

import { FeatureModule1 } from 'my-library';
...
@NgModule({
  imports: [
    ...,
    FeatureModule1,
  ]
})
...

This results in the following error (during building the main project):

ERROR in : Unexpected value 'FeatureModule1 in ./node_modules/my-library/my-library.d.ts'
imported by the module 'AppModule in ./src/app/app.module.ts'.
Please add a @NgModule annotation.

When I import the library module (import { MyLibraryModule } from 'my-library';) into my main application, everything works.

my-library.module.ts looks like this:

import { NgModule } from '@angular/core';

import { FeatureModule1 } from './feature-module-1/feature-module-1.module';
import { FeatureModule2 } from './feature-module-2/feature-module-2.module';

@NgModule({
  imports: [ FeatureModule1, FeatureModule2 ],
  exports: [ FeatureModule1, FeatureModule2 ],
})
export class MyLibraryModule{ }

My public_api.ts exports all modules.

I think it has something to do with packaging process, because in my test project (which is in the same folder as the library) this works without any problems.

I already tried to adapt the building process from @angular/material but it seems, they are doing it a bit different then the official way.

Upvotes: 0

Views: 3370

Answers (1)

Friedrich
Friedrich

Reputation: 1402

The problem was, that I used barrel files in my feature modules (index.ts) that I imported in my public_api.ts like this:

import * from './feature-module-1';

But as described here, you have to point directly at the barrel file. Otherwise the .d.ts file for the package does not contain all exports. So the following line in my public_api.ts fixed the problem:

import * from './feature-module-1/index';

Upvotes: 2

Related Questions