Necros
Necros

Reputation: 3034

Typescript import using path from some root

Is there any simple way to set up so that I can import starting from some root point?

e.g.:

- module1
   \- file1.ts
- module2
   \- file2.ts

in file2 i want to import file1

import { foo } from '../module1/file1'

What I would like to do instead is something like:

import { foo } from 'src/module1/file1'

Angular2 somehow uses this (see https://github.com/angular/angular/blob/master/modules/angular2/src/core/compiler/compiler.ts). I looked into their build process, but it's so complex, I'm not sure how they enabled this.

Upvotes: 4

Views: 6185

Answers (3)

Chris Curnow
Chris Curnow

Reputation: 653

I am working with Angular CLI and the standard structure it produces.

So everything I work with is in src/app.

My main HTTP service is located at src/app/services/httpService.ts.

To get import this service I use:

import { HttpService } from 'app/services/httpService'

I'm not sure if this relies on any special config that Angular CLI does (and I realise Angular CLI wasn't around at the time this question was posted) but it would be worth a try in your environment.

Upvotes: 1

Necros
Necros

Reputation: 3034

https://www.npmjs.com/package/app-module-path seems to be the best solution for node.

Update:

I use it like this

root
  \- module1
  |  \- file1.ts
  \- module2
  |  \- file2.ts
  \- main.ts

main.ts is entry point for the application, and these are the first two lines:

import * as path from 'path';

require('app-module-path').addPath(path.resolve(__dirname, '..'));

then from module2/file2.ts i can do this:

import { Stuff } from 'root/module1/file1';

Upvotes: 1

gilamran
gilamran

Reputation: 7294

All ES6 imports are relative, angular2 are using systemjs to handle all the imports/exports. And in the systemjs configuration you can define a map. (I wouldn't go there)

You have to remember that imports in ES6 are just loading javascript files, so if src is your root, you should be able to just import from /src/module1/files

Upvotes: 1

Related Questions