【问题标题】:short way to import components and modules导入组件和模块的快捷方式
【发布时间】:2017-10-15 21:49:02
【问题描述】:

我使用@angular/cli 创建我的应用程序。当我的应用程序大小增加时,很难提及使用的组件/模块/scss 的导入路径

例如,如果组件结构足够深。要导入,我们必须提到 import {something} from '../../../../someComponent' 继续。

有没有一种方法可以像定义架构一样定义它们

例如:

Schema.json

{
"someComponent":"../../../../someComponent',
 "otherComponent:"../../"
}

我们可以直接导入为import {someComponent} from 'someComponent;,可以在任何地方轻松导入

有没有这样的方法。

【问题讨论】:

  • 谢谢..scss有什么办法可以做到这一点。
  • 我没试过,样式文件和组件类是在同一个地方创建的,所以就是'./whatever.component.scss'
  • 是的,我也试过了,但没用。我试图避免重新定义变量。现在我创建了一个共享的 scss 并在需要的地方导入它。但是当应用程序深入时,这也让我很生气

标签: angular typescript angular-cli


【解决方案1】:

paths可以加在tsconfig.json中:

{
  "compilerOptions": {
    ...,  
    "paths": {
      ...,
      "@app/*": ["app/*"],
      "@components/*": ["components/*"]
    }
  }
}

然后从app/components/ 绝对导入,而不是相对于当前文件:

import {TextInputConfiguration} from "@components/configurations";

【讨论】:

    【解决方案2】:

    您可以在您的应用中使用桶。

    例如你的组件:

    // heroes/folder/deep/another/deep/folder/hero.component.ts
    export class HeroComponent {}
    

    现在您可以在项目的任何文件夹中定义桶,导出此模块(按约定称为 index

    export * from './heroes/folder/deep/another/deep/folder/hero.component.ts'; // relative path to current folder
    

    您可以定义任意数量的桶。

    您可以在docs阅读更多内容

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 2020-09-18
      • 2019-07-01
      • 1970-01-01
      • 2015-07-21
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多