From 02b8bbeffe8454bc2f92dbfa420ad76a9834edcf Mon Sep 17 00:00:00 2001 From: Pavlo Grosse Date: Thu, 21 Nov 2024 09:28:42 +0100 Subject: [PATCH] fix(angular): make scam-to-standalone replace correct module (#29014) ## Current Behavior Without this fix, the regular expression would replace other modules that have old module name in their name. E.g. `MapIconModule` contains `IconModule` and when migrating `IconModule`, the migration would wrongfully update `MapIconModule` to `MapIconComponent`. ## Expected Behavior Migration changes only the Module/Component that's being migrated. --- .../lib/replace-module-usages-with-component.ts | 4 +++- .../scam-to-standalone/scam-to-standalone.spec.ts | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/angular/src/generators/scam-to-standalone/lib/replace-module-usages-with-component.ts b/packages/angular/src/generators/scam-to-standalone/lib/replace-module-usages-with-component.ts index 2eef107f59..3bbcdb31c9 100644 --- a/packages/angular/src/generators/scam-to-standalone/lib/replace-module-usages-with-component.ts +++ b/packages/angular/src/generators/scam-to-standalone/lib/replace-module-usages-with-component.ts @@ -13,7 +13,9 @@ export function replaceModuleUsagesWithComponent( } const fileContents = tree.read(path, 'utf-8'); if (fileContents.includes(moduleName)) { - const moduleNameRegex = new RegExp(moduleName, 'g'); + // Word boundary \b ensures that other modules won't be affected. + // E.g. "MapIconModule" would not be affected when "IconModule" is being migrated. + const moduleNameRegex = new RegExp(`\\b${moduleName}\\b`, 'g'); const newFileContents = fileContents.replace( moduleNameRegex, componentName diff --git a/packages/angular/src/generators/scam-to-standalone/scam-to-standalone.spec.ts b/packages/angular/src/generators/scam-to-standalone/scam-to-standalone.spec.ts index ca125af33d..dc58f5e103 100644 --- a/packages/angular/src/generators/scam-to-standalone/scam-to-standalone.spec.ts +++ b/packages/angular/src/generators/scam-to-standalone/scam-to-standalone.spec.ts @@ -18,9 +18,10 @@ describe('scam-to-standalone', () => { tree.write( 'foo/src/app/mymodule.module.ts', `import { BarComponentModule } from './bar/bar.component'; + import { ExtraBarComponentModule } from './bar/extra-bar.component'; @NgModule({ - imports: [BarComponentModule] + imports: [BarComponentModule, ExtraBarComponentModule] }) export class MyModule {}` ); @@ -49,9 +50,10 @@ describe('scam-to-standalone', () => { expect(tree.read('foo/src/app/mymodule.module.ts', 'utf-8')) .toMatchInlineSnapshot(` "import { BarComponent } from './bar/bar.component'; + import { ExtraBarComponentModule } from './bar/extra-bar.component'; @NgModule({ - imports: [BarComponent], + imports: [BarComponent, ExtraBarComponentModule], }) export class MyModule {} "