angulartypescriptangular-schematics

Angular Schematics - add library to NgModule imports


When using Schematics to generate components in Angular, it will attempt to import the newly generated component into the NgModule, this is mandatory in order for the component to work and saves time.

However, when creating my own schematics, I am unable to find a correct way to do the same and import my library into the app.component.ts's NgModule. When using ng-add schematics, how can you have the schematic automatically add its own entry to the NgModule?

The schematic needs to do two things:

  1. Import the library
  2. Add it to the NgModule imports

Before:

@NgModule({
  declarations: [],
  imports: [],
  exports: []
})
export class appModule { }

After:

import {library} from 'library';

@NgModule({
  declarations: [],
  imports: [library],
  exports: []
})
export class appModule { }

I know a function to do this exists in the angular devkit because the "official" schematics for components and such use it. How would I do the same?


Solution

  • For the first case, something like the code below will help you:

    export function addImportStatement(tree: Tree, filePath: string, type: string, file: string): void {
        let source = getTsSourceFile(tree, filePath);
        const importChange = insertImport(source, filePath, type, file) as InsertChange;
        if (!(importChange instanceof NoopChange)) {
            const recorder = tree.beginUpdate(filePath);
            recorder.insertLeft(importChange.pos, importChange.toAdd);
            tree.commitUpdate(recorder);
        }
    }
    

    For the second one, I don't remember at the momment but you can check angular-cli schematics repository in order to see how it is done for things like modules.

    Cheers!