Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I organize my Angular app folders like a Java package?

How to organize Angular 2 app folder structure like Java packages?

Consider the following project layout:

app
 |_model
 |_component
 |_service

I would like to import foo.service.ts from service to bar.component.ts in component. But as far as I know, Angular 2 import supports only relative paths like /../service/, which seems very clunky solution.

Is there a way to refer folders with absolute bath from root folder, like with Java packages?

like image 249
Tuomas Toivonen Avatar asked May 31 '16 13:05

Tuomas Toivonen


1 Answers

UPDATE 2016-06-01

using npm install typescript@next you can already use this function

I assume that your tree looks like this:

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

You should add in your tsconfig.json the following lines:

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

then you can reference your modules like you do with regular @angular/rxjs modules

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

Note: webpack needs also the following lines in webpack.config.js

resolve: {
    modulesDirectories: [
        'node_modules',
        'app'
    ]
}
like image 147
zpul Avatar answered Oct 13 '22 17:10

zpul