addImportToModule returns empty array of changes

43 Views Asked by At

I'm trying to use angular schematics to add imports to NgModule. I'm using Angular 16.2.5. Here's the code of the logic:

import { addImportToModule, insertImport} from '@schematics/angular/utility/ast-utils';
import * as ts from 'typescript';

function addImport(
  importPath: string,
  importName: string,
  tree: Tree,
  context: SchematicContext
): Tree {
  const modulePath = '/src/app/app.module.ts';

  if (!tree.exists(modulePath)) {
    throw new SchematicsException(`The file ${modulePath} doesn't exist!`);
  }

  const appModuleFile = tree.read(normalize(modulePath))?.toString('utf-8');
  
  if (appModuleFile === null) {
    throw new SchematicsException(`Cannot read the ${modulePath}module!`);
  }

  var source = ts.createSourceFile(
    modulePath,
    appModuleFile!,
    ts.ScriptTarget.Latest,
    true
  );

  const importChange = insertImport(source, modulePath, importName, importPath, true)
  const importsChanges = addImportToModule(source, modulePath,importName,importPath);

  const changes = [importChange, ...importsChanges]
  const importRecorder = tree.beginUpdate(modulePath);

  for (const change of changes) {
    context.logger.debug(change.description);
    if (change instanceof InsertChange) {
      context.logger.info('Found change.');
      importRecorder.insertLeft(change.pos, change.toAdd);
    }
    else{
      context.logger.info('Something else');
    }
  }

  tree.commitUpdate(importRecorder);

  return tree;
}

For some reason, insertImport is working as expected, but the addImportToModule is not - it's neither inserting the module nor inserting the module into NgModule imports array. The function itself return the empty array.

Here's the AppModule I'm trying to update (located at src/app/app.module.ts:

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

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

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

I've been going over many example in the internet, but they all look similar and nothing works for me. What am I missing?

1

There are 1 best solutions below

1
Paweł Poręba On

I've found the issue, finally - will post here, maybe someone finds that useful.

I have two packages outdated (here are the corrected versions):

@angular-devkit/build-angular": "16.2.5"
"ng-packagr": "16.2.3"

Also, I changed the import from: import * as ts from 'typescript'; to import * as ts from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript'; as it was required to build the project after the updates.