Lyubimov Roman
Lyubimov Roman

Reputation: 1269

Typescript - simplify imports

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.

Upvotes: 1

Views: 947

Answers (2)

Lyubimov Roman
Lyubimov Roman

Reputation: 1269

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".

Upvotes: 1

LordTribual
LordTribual

Reputation: 4249

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.

Upvotes: 3

Related Questions