angular - 防止 AOT 从编译中排除组件
问题描述
我一直在开发一个包含很多动态组件的 Angular 应用程序,而且我还编写了一个注释来注册这些动态组件。
让我们看看代码:
- 注解。(为了更好地理解,我对此进行了简化)。
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;
};
};
- 动态组件
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
来重现问题。
解决方案
推荐阅读
- asp.net - 我无法访问 vb.net 内容页面中母版页的功能
- javascript - Ajax setTimeout 函数
- java - Java - 两个 do while 循环不适用于扫描仪
- java - 在 Java JDBC 中苦苦挣扎:使用 Intellij 的 sqlite 连接
- c - 无法弄清楚 c 中的 OPENMP 程序中发生竞争条件的位置
- mongodb - 组规范必须包含 _id
- python - 是否可以在弹出窗口中显示 CSV 数据?
- r - 探索 R 中的组合因子
- python - Django 显示单选按钮选择
- android - java.lang.IllegalArgumentException:无法为类创建@Body 转换器