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.
This commit is contained in:
Pavlo Grosse 2024-11-21 09:28:42 +01:00 committed by GitHub
parent 60a9f81dac
commit 02b8bbeffe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 7 additions and 3 deletions

View File

@ -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

View File

@ -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 {}
"