Skip to content

Commit

Permalink
fix(migrations): generate forwardRef for same file imports (#48898)
Browse files Browse the repository at this point in the history
Adds some logic that will generate a `forwardRef` if necessary when adding imports.

PR Close #48898
  • Loading branch information
crisbeto authored and dylhunn committed Feb 2, 2023
1 parent d014503 commit ba38178
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,18 @@ function getComponentImportExpressions(
ref.node.getSourceFile(), importLocation.symbolName, importLocation.moduleSpecifier);
imports.push(identifier);
} else {
imports.push(ts.factory.createIdentifier(importLocation.symbolName));
const identifier = ts.factory.createIdentifier(importLocation.symbolName);

if (importLocation.isForwardReference) {
const forwardRefExpression =
tracker.addImport(ref.node.getSourceFile(), 'forwardRef', '@angular/core');
const arrowFunction = ts.factory.createArrowFunction(
undefined, undefined, [], undefined, undefined, identifier);
imports.push(
ts.factory.createCallExpression(forwardRefExpression, undefined, [arrowFunction]));
} else {
imports.push(identifier);
}
}

seenImports.add(importLocation.symbolName);
Expand Down
40 changes: 40 additions & 0 deletions packages/core/schematics/test/standalone_migration_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1254,6 +1254,46 @@ describe('standalone migration', () => {
`));
});

it('should generate a forwardRef for forward reference within the same file', async () => {
writeFile('decls.ts', `
import {Component, Directive} from '@angular/core';
@Component({
selector: 'comp',
template: '<div my-dir></div>'
})
export class MyComp {}
@Directive({selector: '[my-dir]'})
export class MyDir {}
`);

writeFile('module.ts', `
import {NgModule} from '@angular/core';
import {MyComp, MyDir} from './decls';
@NgModule({declarations: [MyComp, MyDir]})
export class Mod {}
`);

await runMigration('convert-to-standalone');

expect(stripWhitespace(tree.readContent('decls.ts'))).toEqual(stripWhitespace(`
import {Component, Directive, forwardRef} from '@angular/core';
@Component({
selector: 'comp',
template: '<div my-dir></div>',
standalone: true,
imports: [forwardRef(() => MyDir)]
})
export class MyComp {}
@Directive({selector: '[my-dir]', standalone: true})
export class MyDir {}
`));
});

it('should remove a module that only has imports and exports', async () => {
writeFile('app.module.ts', `
import {NgModule} from '@angular/core';
Expand Down

0 comments on commit ba38178

Please sign in to comment.