diff --git a/packages/schematics/angular/utility/ast-utils.ts b/packages/schematics/angular/utility/ast-utils.ts index 96479d02e964..2442f0661793 100644 --- a/packages/schematics/angular/utility/ast-utils.ts +++ b/packages/schematics/angular/utility/ast-utils.ts @@ -395,7 +395,7 @@ export function addSymbolToNgModuleMetadata( // Get the indentation of the last element, if any. const text = node.getFullText(source); const matches = text.match(/^\r?\n\s*/); - if (matches.length > 0) { + if (matches && matches.length > 0) { toInsert = `,${matches[0]}${metadataField}: [${symbolName}]`; } else { toInsert = `, ${metadataField}: [${symbolName}]`; diff --git a/packages/schematics/angular/utility/ast-utils_spec.ts b/packages/schematics/angular/utility/ast-utils_spec.ts index 1ea30a5126a5..bd694b6499a3 100644 --- a/packages/schematics/angular/utility/ast-utils_spec.ts +++ b/packages/schematics/angular/utility/ast-utils_spec.ts @@ -151,4 +151,19 @@ describe('ast utils', () => { const output = applyChanges(modulePath, moduleContent, changes || []); expect(output).toMatch(/imports: \[HelloWorld],\r?\n/m); }); + + it('should handle NgModule with no newlines', () => { + const moduleContent = ` + import { BrowserModule } from '@angular/platform-browser'; + import { NgModule } from '@angular/core'; + + @NgModule({imports: [BrowserModule], declarations: []}) + export class AppModule { } + `; + const source = getTsSource(modulePath, moduleContent); + const changes = addExportToModule(source, modulePath, 'FooComponent', './foo.component'); + const output = applyChanges(modulePath, moduleContent, changes); + expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); + expect(output).toMatch(/exports: \[FooComponent\]/); + }); });