合并组件以避免导入多个 类

Consolidate components to avoid import of multiple classes

我的选项卡模块需要两个组件。

<tabs>

<tab>

要使用此选项卡,我必须像这样导入:

import { Tabs, Tab } from '../../components/tabs/tabs.component';

在这种情况下,它们只有两个组件。但是我正在规划更多 "child-components" 的组件。有没有办法合并它们?

Typescript 允许您import the entire module into a single variable,并使用它来访问模块导出。

在您的情况下,如果您有一个 '../../components/tabs/tabs.component'; 文件,其中包含以下几行:

export class Tab {
...
export class Tabs {

您可以在另一个文件中通过以下方式将它们导入单个变量:

import * as TabsModule from '../../components/tabs/tabs.component';

然后使用 TabsModule 作为前缀访问它们。换句话说:

  • Tab 变为 TabsModule.Tab;和
  • Tabs 变为 TabsModule.Tabs.

Typescript handbook on Modules 解释得很好。


Ps.: 根据 Angular2 Style Guide. The recommendation is to declare each component into its own file and create an index file which exports them at once -- see Create Import Barrels,在一个文件中包含多个组件(TabTabs 都在 tabs.component.ts 中)被认为是一种不好的做法。