4

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.

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

My app is actually a node app, so typescript is transpiled to ES5 and require. I don't think you can import from root with require, unless you hack it somehow or force the compiler to generate correct relative path for you.
1

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';

2 Comments

Did you manage to get app-module-path to work? Because it does not work for me using it.
Yes, see updated answer. This worked for me for any version of node I ran.
1

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.

1 Comment

This is a feature of typescript compiler, that has been improved a lot since this question, there is also a setting where you can configure custom paths (typescriptlang.org/docs/handbook/module-resolution.html). Also there are (or used to be) some differences between node and browser module resolution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.