首页 > 解决方案 > 防止 AOT 从编译中排除组件

问题描述

我一直在开发一个包含很多动态组件的 Angular 应用程序,而且我还编写了一个注释来注册这些动态组件。

让我们看看代码:

  1. 注解。(为了更好地理解,我对此进行了简化)。
import { Type, Component } from '@angular/core';

export const componentsMap: { [key: string]: Type<Component> } = {};

export const DynamicComponent = (componentId: string) => {
  return (component: Component) => {
    componentsMap[componentId] = component;
    return component;
  };
};
  1. 动态组件
import { Component } from '@angular/core';
import { DynamicComponent } from './dynamic-component.decorator';

@Component({
  selector: 'dynamic-test',
  template: `<h1>I'm alive!</h1>`
})
@DynamicComponent('dynamicComponent')
export class DynamicTestComponent {}

然后,使用 Component Factory Resolver 创建组件并将其注入 ng-container (我将跳过这部分,因为它没有问题)。

如果应用程序是在 JIT 中编译的,这可以正常工作。如果应用在 AOT 中编译,该组件将不会包含在编译的 js 文件中。据我了解,这是因为 AOT 在应用程序中看不到任何用法(仅在模块中声明)并将其从编译中排除。关闭 AOT 编译不是一种选择,因为最终应用程序的大小会太大。

我被告知让它工作的唯一方法是这样做:

@NgModule({
    declarations: [DynamicTestComponent],
    imports: [CommonModule]
})
export class TestModule {
    static declaration = [DynamicTestComponent]
}

此解决方案比关闭 AOT 更好,但我一直在寻找更直观的解决方案。

你知道还有什么可以做的,所以在 AOT 编译过程中不会排除组件吗?

ps 我在 StackBlitz 上用上面的代码创建了一个示例,所以你可以下载它。https://stackblitz.com/edit/angular-ivy-souyuz 您可以在本地运行它ng serve --configuration production来重现问题。

标签: angulartypescriptangular-dynamic-components

解决方案


推荐阅读