Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

typescript - Angular2 - root relative imports

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Answer

As of TypeScript 2.0 you can set tsconfig.json properties baseUrl as following:

{
  "compilerOptions": {
    "baseUrl": "app"
}

Then, you might use your desired manner of importing components, like:

import { Calendar } from 'components/calendar';

Appendix

Fallback paths resolution

An important consideration is that specifying baseUrl option causes TypeScript compilator to:

  1. Look up a path with regards to baseUrl
  2. On failed resolution (module not found), look up a path with regards to moduleResolution option

SystemJS

Since SystemJS is heavily used in Angular development stage, be sure to accordingly config also systemjs.config.js, so that it resolves paths correctly.


Source and further details: https://github.com/Microsoft/TypeScript/issues/5039


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...