1

Is there way to import modules with alias? E.g. I have angular service in folder common/services/logger/logger.ts. How to make import looks like import {Logger} from "services" where "services" contains all my services?

I've looked at this and this but didn't understand how I can use it.

Lyubimov Roman
  • 1,269
  • 15
  • 27
  • You want to import a class called `Logger` from a file called `services`? – LordTribual May 25 '16 at 12:25
  • I want agregate all my classes in one file and make it accessable by "services" name. Because I don't really want to write always full path to each module when I want to import it. – Lyubimov Roman May 25 '16 at 12:26
  • The same as `import {Injectable} from "@angular/core";`. So "@angular/core" is a kind of alias. Is there way to do it? – Lyubimov Roman May 25 '16 at 12:29
  • 1
    it's called a [barrel](https://angular.io/docs/ts/latest/glossary.html). [this](http://stackoverflow.com/questions/37082601/how-to-import-a-barrel-by-folder-name-only/37207293#37207293) might do what you want – Ankit Singh May 25 '16 at 12:42
  • Thanks! It solves the problem. It is time to inject webpack in ionic 2 app :) – Lyubimov Roman May 25 '16 at 12:54

2 Answers2

3

Create one file that contains all of your services and give it a name, e.g. services.ts. That file can be seen as a barrels, because it will contain and export all of your services. The file could look like this:

export * from './logger/logger';
export * from ...;
etc.

Now you can import this single file as follow:

import * as Services from 'common/services';

Then you can access your servies via Services.Logger, or directly import the service you want via:

import {Logger} from 'common/services';

Note, you have change the paths since this is just an example. For more information about this technique, have a look here.

LordTribual
  • 4,219
  • 2
  • 28
  • 38
1

To solve this problem I used webpack. If you want to import dependencies everywhere you want, you will need to add alias in webpack config. For example, you have folder shared in root with services folders in it. Folder services should have index.ts that exports all services you need (e.g Logger). So alias would be "services" => "shared/services".

To make autocomplete work in WebStorm you just need to mark shared folder as a "Resource root".

Lyubimov Roman
  • 1,269
  • 15
  • 27
  • I don't see how this solves the problem. How does `services` or anyone else know that he wants to import `Logger`, and how does he get `Logger` from `ServiceName`? –  Jul 17 '16 at 12:17
  • It is just shorter path to folder that available everywhere. Do you mean that I need to describe how to configurate webpack and what structure of folders should be? – Lyubimov Roman Jul 17 '16 at 13:58
  • I have updated my answer, is it clear now? `ServiceName` is actually `Logger` itself that should be exported in `index.ts` in `services` folder. – Lyubimov Roman Jul 17 '16 at 14:04