2017-07-25 133 views
0

我创建了一个Angular2应用程序,我使用Webapack捆绑了这个应用程序。 现在目标文件大小增加了超过15MB,包括依赖模块。动态加载Angular2模块

现在我想加载基于需求的依赖模块。

我有多个主菜单,每个菜单都包含一个带有相关组件的模块。现在我想基于用户菜单选择异步加载依赖模块。

+0

看一看这个 - 你曾经想知道托德座右铭代码分裂和懒加载的一切。 https://toddmotto.com/lazy-loading-angular-code-splitting-webpack –

+0

嘿,没有[我的回答](https://stackoverflow.com/a/45311283/2545680)有帮助吗? –

回答

0

您可以使用动态模块加载和JIT编译器轻松完成此操作。这是一般的方法:

constructor(private injector: Injector, private compiler: Compiler) 

loadModule(moduleName) { 
    import(pathToModule).then((module)=>{ 
     const moduleClass = module.moduleName; 
     const moduleFactory = this.compiler.compileModuleSync(moduleClass); 
     const moduleRef = moduleFactory.create(this.injector); 
     const componentFactoryResolver = moduleRef.componentFactoryResolver; 

     // then you can use the resolver to get components 
     const f = componentFactoryResolver.resolveComponentFactory(MyComponent); 
    }) 
} 

了解更多关于动态组件的int Here is what you need to know about dynamic components in Angular