Skip to content

@defer fails when using components exported with alias #63965

Closed

Description

@dawidskowron

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

No

Description

When using the @defer block with a component that is exported under an alias, Angular throws an error:
ERROR TypeError: Cannot read properties of undefined (reading 'ɵcmp')

Image

If the same component is used under its original name, everything works as expected.

@Component({
  ...
})
export class CounterComponent {}
// ✅ Works fine when exported original name
// export { CounterComponent } from './counter.component';

// ❌ Fails when exported under an alias
export { CounterComponent as MyCounterCmp } from './counter.component';
// ✅ Works fine when imported as original name
// import { CounterComponent } from './counter';

// ❌ Fails when imported alias MyCounterCmp
import { MyCounterCmp } from './counter';

@Component({
  ...
  template: `
    @defer {
      <my-counter-cmp />
    }
  `,
  imports: [MyCounterCmp],
})

Please provide a link to a minimal reproduction of the bug

https://stackblitz.com/edit/stackblitz-starters-exos4wjy?file=src%2Fapp%2Fapp.ts

Please provide the exception or error you saw

ERROR TypeError: Cannot read properties of undefined (reading 'ɵcmp')

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 20.3.2
Node: 20.19.1
Package Manager: npm 10.8.2
OS: linux x64
    

Angular: 20.3.1
... common, compiler, compiler-cli, core, platform-browser
... platform-server

Package                      Version
------------------------------------
@angular-devkit/architect    0.2003.2
@angular-devkit/core         20.3.2
@angular-devkit/schematics   20.3.2
@angular/build               20.3.2
@angular/cli                 20.3.2
@angular/ssr                 20.3.2
@schematics/angular          20.3.2
rxjs                         7.8.2
typescript                   5.9.2

Anything else?

I used the --no-hmr flag in StackBlitz to prevent deferred block dependencies from being loaded eagerly. With HMR enabled, Angular forces all @defer dependencies to load immediately, which defeats the purpose of testing their lazy behavior.

Activity

  1. SkyZeroZx commented on Sep 20, 2025

    @SkyZeroZx
    Contributor

    I reviewed the code and debugged the core logic related to defer instructions (specifically those tied to the IDLE state).

    From the investigation:

    The dependenciesFn() generated during compiler parsing of defer blocks does not resolve the correct reference.

    As a result, the trigger fails and an unexpected error is thrown.

    Image

    While debugging further in my node_modules, I found that the issue might be related to the compiler function compileComponentMetadataAsyncResolver.

    By adding console.log statements, I was able to trace the file path, but it seems the problem could be tied to a missing or incorrect case when handling renamed files in the index.ts with some alias to components (or a similar mapping). This might explain why the reference fails to resolve properly.

    export function compileComponentMetadataAsyncResolver(
      dependencies: R3DeferPerComponentDependency[],
    ): o.ArrowFunctionExpr {
      const dynamicImports = dependencies.map(({symbolName, importPath, isDefaultImport}) => {
        // e.g. `(m) => m.CmpA`
        const innerFn =
          // Default imports are always accessed through the `default` property.
          o.arrowFn(
            [new o.FnParam('m', o.DYNAMIC_TYPE)],
            o.variable('m').prop(isDefaultImport ? 'default' : symbolName),
          );
    
        // e.g. `import('./cmp-a').then(...)`
        return new o.DynamicImportExpr(importPath).prop('then').callFn([innerFn]);
      });
    
      // e.g. `() => [ ... ];`
      return o.arrowFn([], o.literalArr(dynamicImports));
    }

    EDIT :
    Possible need some parsing to alias in compiler cli resolveAllDeferredDependencies in class ComponentDecoratorHandler

     private resolveAllDeferredDependencies(
        resolution: Readonly<ComponentResolutionData>,
      ): R3DeferPerComponentDependency[] {
        const seenDeps = new Set<ClassDeclaration>();
        const deferrableTypes: R3DeferPerComponentDependency[] = [];
        // Go over all dependencies of all defer blocks and update the value of
        // the `isDeferrable` flag and the `importPath` to reflect the current
        // state after visiting all components during the `resolve` phase.
        for (const [_, deps] of resolution.deferPerBlockDependencies) {
          for (const deferBlockDep of deps) {
            const node = deferBlockDep.declaration.node;
            const importDecl = resolution.deferrableDeclToImportDecl.get(node) ?? null;
            if (importDecl !== null && this.deferredSymbolTracker.canDefer(importDecl)) {
              deferBlockDep.isDeferrable = true;
              deferBlockDep.importPath = (importDecl.moduleSpecifier as ts.StringLiteral).text;
              deferBlockDep.isDefaultImport = isDefaultImport(importDecl);
  2. added
    area: core
    core: defer
    on Sep 20, 2025
  3. added this to the needsTriage milestone on Sep 20, 2025
  4. SkyZeroZx commented on Sep 20, 2025

    @SkyZeroZx
    Contributor

    I think I’ve fixed the behavior. The issue required some changes in the compiler CLI to correctly parse the data. I tested a local fix by modifying the ComponentDecoratorHandler function, specifically in resolveAllDeferredDependencies, to properly resolve the import information. With this adjustment, the error is resolved.

    I’ll continue working to propose this fix.

    Image
  5. thePunderWoman commented on Sep 22, 2025

    @thePunderWoman
    Contributor

    Closing since #63966 has been merged.

  6. angular-automatic-lock-bot commented on Oct 23, 2025

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  7. locked and limited conversation to collaborators on Oct 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corecore: defer

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions