【问题标题】:How can I organize my Angular app folders like a Java package?如何像 Java 包一样组织我的 Angular 应用程序文件夹?
【发布时间】:2016-05-31 13:37:43
【问题描述】:

如何像 Java 包一样组织 Angular 2 应用程序文件夹结构?

考虑以下项目布局:

app
 |_model
 |_component
 |_service

我想将 service 中的 foo.service.ts 导入 component 中的 bar.component.ts。但据我所知,Angular 2 import 只支持像/../service/ 这样的相对路径,这似乎是非常笨拙的解决方案。

有没有办法从 根文件夹 引用具有绝对浴的文件夹,就像 Java 包一样?

【问题讨论】:

    标签: javascript module typescript angular systemjs


    【解决方案1】:

    2016-06-01 更新

    使用npm install typescript@next你已经可以使用这个功能了

    我假设你的树看起来像这样:

    node_modules
     |_@angular
     |_rxjs
    app
     |_model
     |_component
     |_service
    package.json
    tsconfig.json
    

    您应该在 tsconfig.json 中添加以下行:

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "*": [
            "app/*",
            "node_modules/*"
          ]
        }
      }
    }
    

    然后您可以像使用常规 @angular/rxjs 模块一样引用您的模块

    import { MyService } from 'service/MyService';
    import { Component } from '@angular/core';
    import { Observable } from 'rxjs';
    

    注意:webpack 还需要 webpack.config.js 中的以下行

    resolve: {
        modulesDirectories: [
            'node_modules',
            'app'
        ]
    }
    

    【讨论】:

    • 正如你已经提到的,这是自去年 9 月以来一直在讨论的问题 (github.com/Microsoft/TypeScript/issues/5039)。我只是很惊讶他们以前没有考虑过。使用“../../../”太麻烦了。感谢您的回答。 TS@2.0 即将推出; Beta 版已于 6 天前发布 :)
    【解决方案2】:

    还没有,Typescript 2.0 应该很快就会出现

    看这里 https://github.com/Microsoft/TypeScript/issues/5039

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-09
      • 2018-11-25
      • 2011-05-02
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多