2016-02-12 100 views
13

我已經爲Angular 1編寫了一個大應用程序,並且需要使用AMD來支持延遲加載和結構化。該應用程序不使用路線,但應用程序的一部分,如HTML,CSS和Javascript(角度模塊)被延遲加載。Angular 2延遲加載技術

現在我想更改爲Angular 2,並且我正在尋找HTML,CSS和JS(角度)內容的最佳延遲加載技術,它不依賴於路由並且不依賴於數千個不同的JavaScript構架。

所以延遲加載路由組件似乎很簡單: http://blog.mgechev.com/2015/09/30/lazy-loading-components-routes-services-router-angular-2

,但你會怎麼做到沒有對路由的情況? 你會推薦類似webpack的東西,還是應該保持requireJS?是否有像角度2的OClazyload?或者甚至在沒有任何框架的情況下,它與Angular 2有什麼關係?

我是「保持簡單」的朋友,我真的希望保持它儘可能的小而簡單。

謝謝!

回答

3

Angular 2基於Web組件。最簡單的方法(如你所說的「簡單化」)是使用路線和組件。 您也可以通過在html中使用指令來加載組件。例如:

@Component({ 
    selector: 'my-component', // directive name 
    templateUrl: './app/my.component.html', 
    directives: [] 
}) 
export class MyComponent {} 



@Component({ 
    selector: 'root-component', // directive name 
    directives: [MyComponent], 
    template: '<my-component></my-component>', 
}) 
export class myComponent {} 
如果您修改模板中包含 <my-component>

動態它將動態加載的組件。這不是最佳做法。

對於角度2有一個dynamic component loader,但這不像使用路由或指令那麼簡單。它將創建一個Component的實例並將其附加到位於另一個Component實例的Component View內的View Container。

有了它,你可以使用:

@Component({ 
    selector: 'child-component', 
    template: 'Child' 
}) 
class ChildComponent { 
} 
@Component({ 
    selector: 'my-app', 
    template: 'Parent (<child id="child"></child>)' 
}) 
class MyApp { 
    constructor(dcl: DynamicComponentLoader, injector: Injector) { 
    dcl.loadAsRoot(ChildComponent, '#child', injector); 
    } 
} 
bootstrap(MyApp); 

產生的DOM:

<my-app> 
    Parent (
    <child id="child">Child</child> 
) 
</my-app> 

還有另一種選擇(看上面angular2鏈接),可以在其中選擇提供供應商配置噴油器爲此組件實例調配。

希望這會有所幫助。

2

使用angular 2最新版本,我們可以使用loadchildren屬性執行延遲加載。 例如: { 路徑: '客戶', loadChildren: './customer.module#Customer2Module?chunkName=Customer' },

在我使用的WebPack捆綁此上述例子(角2路由器裝載機)+ Anguar 2路由延遲加載模塊。