任何人都知道如何手动加载模块,而无需使用 Route.loadChildren?
您可以使用SystemJsNgModuleLoader来获取模块的工厂:
this.loader.load('./src/lazy.module#TestModule').then((factory: NgModuleFactory) => {
console.log(factory);
});
对于Angular 8,请参见 角度8中的延迟加载模块
它看起来像这样:
lazy.module.ts
@Component({
selector: 'test',
template: `I'm lazy module`,
})
export class Test {}
@NgModule({
imports: [CommonModule],
declarations: [Test],
entryComponents: [Test]
})
export class LazyModule {
static entry = Test;
}
应用程序
import {
Component, NgModule, ViewContainerRef,
SystemJsNgModuleLoader, NgModuleFactory,
Injector} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
Test lazy loading module
`,})
export class AppComponent {
constructor(
private loader: SystemJsNgModuleLoader,
private inj: Injector,
private vcRef: ViewContainerRef) {}
ngOnInit() {
this.loader.load('./src/lazy.module#LazyModule')
.then((moduleFactory: NgModuleFactory) => {
const moduleRef = moduleFactory.create(this.inj);
const entryComponent = (moduleFactory.moduleType).entry;
const compFactory =
moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
this.vcRef.createComponent(compFactory);
});
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
providers: [SystemJsNgModuleLoader],
bootstrap: [ AppComponent ]
})
export class AppModule {}
this.loader.load('./src/test.module#TestModule').then((factory: NgModuleFactory) => {
console.log(factory);
});
柱塞示例
有两种方法可以为AOT预编译模块:
1)Angular CLI lazyModules选项(自Angular 6起)
使用angular / cli内置功能:
{
"projects": {
"app": {
"architect": {
"build": {
"options": {
"lazyModules": [ <====== add here all your lazy modules
"src/path-to.module"
]
}
}
}
}
}
}
看到
@RomainLT答案
速度需求:Angular文章中的延迟加载非路由模块,了解更多详细信息
2)从RouterModule使用ProvideRoutes
app.module.ts
providers: [
SystemJsNgModuleLoader,
provideRoutes([
{ loadChildren: 'app/lazy/lazy.module#LazyModule' }
])
],
app.component.ts
export class AppComponent implements OnInit {
title = 'Angular cli Example SystemJsNgModuleLoader.load';
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private loader: SystemJsNgModuleLoader, private inj: Injector) {}
ngOnInit() {
this.loader.load('app/lazy/lazy.module#LazyModule').then((moduleFactory: NgModuleFactory) => {
const entryComponent = (moduleFactory.moduleType).entry;
const moduleRef = moduleFactory.create(this.inj);
const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
this.container.createComponent(compFactory);
});
}
}
Github回购angular-cli-lazy
使用webpack和AOT延迟加载
使用ngc进行编译
通过使用以下工厂进行初始化编译器
export function createJitCompiler () {
return new JitCompilerFactory([{useDebug: false, useJit: true}]).createCompiler();
}
Github回购