Tuesday, June 05, 2018

Angular 5: Importing classes from their module, rather than importing them individually

Caveat lector: while this works, meaning it compiles and runs, you might have problems when you are trying to package your work into npm packages. When ng-packagr is used with such a system (often found in older versions of Angular as index.ts files) it throws a really unhelpful exception: TypeError: Cannot read property 'module' of undefined somewhere in bundler.js. The bug is being tracked here, but it doesn't seem to be much desire to address it. Apparently, I have rediscovered the concept of barrel, which now seems to have been abandoned and even completely expunged from Angular docs.

Have you ever seen enormous lists of imports in Angular code and you wondered why couldn't they be more compact? My solution for it is to re-export from a module all the classes that I will need in other modules. Here is an example from LocationModule, which contains a service and a model for locations:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LocationService } from './services/location.service';
import { LocationModel } from './models/location-model';
 
@NgModule({
  imports: [ CommonModule ],
  providers: [ LocationService ]
})
export class LocationModule { }
 
export { LocationModel, LocationService };

Thing to note: I am exporting the model and the service right away. Now I can do something like
import { LocationModule, LocationModel, LocationService } from '../../../location/location.module';
instead of
import { LocationModule } from '../../../location/location.module';
import { LocationModel } from '../../../location/models/location-model';
import { LocationService } from '../../../location/services/location.service';

0 comments: