2017-07-25 132 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