使用 Barrel

例如,沒有 Barrel,消費者需要三個 import 語句:

import { HeroComponent } from '../heroes/hero.component.ts';                                
import { Hero }          from '../heroes/hero.model.ts';                                      
import { HeroService }   from '../heroes/hero.service.ts';

我們可以通過在同一個元件資料夾中建立檔案來新增 Barrel。在這種情況下,該資料夾名為 heroes,名為 index.ts(使用約定),匯出所有這些項:

export * from './hero.model.ts';   // re-export all of its exports
export * from './hero.service.ts'; // re-export all of its exports                           
export { HeroComponent } from './hero.component.ts'; // re-export the named thing

現在,消費者可以從 Barrel 中匯入所需的東西。
import { Hero, HeroService } from '../heroes/index';

不過,這可能會成為一個很長的路線; 這可以進一步減少。

import * as h from '../heroes/index';

這已經相當減少了! * as h 將所有模組和別名匯入為 h