任何人都知道如何手动加载模块,而无需使用
Route.loadChildren?
您可以使用SystemJsNgModuleLoader 获取模块的工厂:
this.loader.load('./src/lazy.module#TestModule').then((factory: NgModuleFactory<any>) => {
console.log(factory);
});
对于 Angular 8,请参阅
Lazy load module in angular 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;
}
app.ts
import {
Component, NgModule, ViewContainerRef,
SystemJsNgModuleLoader, NgModuleFactory,
Injector} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `<h2>Test lazy loading module</h2>`,
})
export class AppComponent {
constructor(
private loader: SystemJsNgModuleLoader,
private inj: Injector,
private vcRef: ViewContainerRef) {}
ngOnInit() {
this.loader.load('./src/lazy.module#LazyModule')
.then((moduleFactory: NgModuleFactory<any>) => {
const moduleRef = moduleFactory.create(this.inj);
const entryComponent = (<any>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<any>) => {
console.log(factory);
});
Plunker Example
AOT的预编译模块有两种选择:
1) Angular CLIlazyModules 选项(从 Angular 6 开始)
使用 angular/cli 内置功能:
{
"projects": {
"app": {
"architect": {
"build": {
"options": {
"lazyModules": [ <====== add here all your lazy modules
"src/path-to.module"
]
}
}
}
}
}
}
见
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<any>) => {
const entryComponent = (<any>moduleFactory.moduleType).entry;
const moduleRef = moduleFactory.create(this.inj);
const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
this.container.createComponent(compFactory);
});
}
}
Github repo angular-cli-lazy
使用 webpack 和 AOT 进行延迟加载
使用 ngc 编译
使用以下工厂初始化编译器
export function createJitCompiler () {
return new JitCompilerFactory([{useDebug: false, useJit: true}]).createCompiler();
}
Github repo