diff --git a/packages/schematics/angular/utility/ast-utils.ts b/packages/schematics/angular/utility/ast-utils.ts index 2442f0661793..e81f85919149 100644 --- a/packages/schematics/angular/utility/ast-utils.ts +++ b/packages/schematics/angular/utility/ast-utils.ts @@ -455,8 +455,8 @@ export function addSymbolToNgModuleMetadata( position = node.getEnd(); // Get the indentation of the last element, if any. const text = node.getFullText(source); - if (text.match('^\r?\r?\n')) { - toInsert = `,${text.match(/^\r?\n\s+/)[0]}${metadataField}: [${symbolName}]`; + if (text.match(/^\r?\r?\n/)) { + toInsert = `,${text.match(/^\r?\n\s*/)[0]}${metadataField}: [${symbolName}]`; } else { toInsert = `, ${metadataField}: [${symbolName}]`; } @@ -469,7 +469,7 @@ export function addSymbolToNgModuleMetadata( // Get the indentation of the last element, if any. const text = node.getFullText(source); if (text.match(/^\r?\n/)) { - toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${symbolName}`; + toInsert = `,${text.match(/^\r?\n(\r?)\s*/)[0]}${symbolName}`; } else { toInsert = `, ${symbolName}`; } diff --git a/packages/schematics/angular/utility/ast-utils_spec.ts b/packages/schematics/angular/utility/ast-utils_spec.ts index bd694b6499a3..21bd96d6e764 100644 --- a/packages/schematics/angular/utility/ast-utils_spec.ts +++ b/packages/schematics/angular/utility/ast-utils_spec.ts @@ -11,7 +11,11 @@ import { HostTree } from '@angular-devkit/schematics'; import * as ts from 'typescript'; import { Change, InsertChange } from '../utility/change'; import { getFileContent } from '../utility/test'; -import { addExportToModule, addSymbolToNgModuleMetadata } from './ast-utils'; +import { + addDeclarationToModule, + addExportToModule, + addSymbolToNgModuleMetadata, +} from './ast-utils'; function getTsSource(path: string, content: string): ts.SourceFile { @@ -73,6 +77,15 @@ describe('ast utils', () => { expect(output).toMatch(/exports: \[FooComponent\]/); }); + it('should add declarations to module if not indented', () => { + moduleContent = tags.stripIndents`${moduleContent}`; + const source = getTsSource(modulePath, moduleContent); + const changes = addDeclarationToModule(source, modulePath, 'FooComponent', './foo.component'); + const output = applyChanges(modulePath, moduleContent, changes); + expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); + expect(output).toMatch(/declarations: \[\nAppComponent,\nFooComponent\n\]/); + }); + it('should add metadata', () => { const source = getTsSource(modulePath, moduleContent); const changes = addSymbolToNgModuleMetadata(source, modulePath, 'imports', 'HelloWorld');