[Fixed] Angular2 – root relative imports

Issue

I have a problem with imports in angular2/typescript. I’d like to use imports with some root like ‘app/components/calendar’, instead only way I am able to use is something like:

//app/views/order/order-view.ts
import {Calendar} from '../../components/calendar 

where Calendar is defined like:

//app/components/calendar.ts
export class Calendar {
}

and this obviously gets much worse the lower in hierarchy you go, deepest is ‘../../..’ but it is still very bad and brittle. Is there any way how to use paths relative to project root?

I am working in Visual Studio, and relative imports seem to be the only thing that makes VS able to recognize these imports.y

Solution

UPDATE

Just don’t use this solution. Embrace node module resolution algorithm.
Community rests on it, so everything will break apart if you try to do otherwise. Use aliases or some of the other provided solutions.

Short answer
There’s a way but you shouldn’t do it.
Set the compilerOption "moduleResolution" to "classic".

Long answer

Are you using tsconfig.json? I assume you are. I’ve been looking a way to make statements such as import someModule = require ("../../../../someModule" into import someModule=require("src/path/to/someModule").
I found after hours wasted that tsc may use different algorithms for module resolution. I’m using atom and it creates the tsconfig.json with the compilerOption property moduleResolution set to "node" and it uses the shitty (excuse my french) module resolution algorithm of node. I just put "classic" and started working the obvious way.

Leave a Reply

(*) Required, Your email will not be published