0

I want to import components and services without any path prefix, like this:

import { CarService } from 'services/car.service';

From files in a Angular app structure that looks like this:

carproject
   src
      app (from here)
          components (from here)
             base (from here)
          pages (from here)
          services (from here)

Currently tscongif.json in carproject folder contains this base URL:

"baseUrl": "./src",

And tscongif.app.json in src folder:

"baseUrl": "app" 

Application actually allows to make imports in the format i provided on top of this question. The application starts properly.

But Visual Code does not seem to understand it. And shows error:

Cannot find module 'services/car.service'.ts(xxx)

How to properly configure baseUrls so i will be able to import components and services without path prefixes from places indicated above, and so that Visual Studio Code will be able to find these imports also?

1

1 Answer 1

1

You should change your tsconfig.json. I'm assum that your services code in services folder so I will change the config

"baseUrl": "./",
"paths": {
   "services/*": ["src/app/services/*"],
 },

Then you can import like this

import { CarService } from 'services/car.service';
Sign up to request clarification or add additional context in comments.

6 Comments

As a addition you can then also provide a index.ts in that folder so that you can import everything from just like this @services/index or @services
@JohnnyDevNullThanks for comment. If i will use index.ts and import everything, does it mean i will not need to import stuff in each component and service?
@Tony Ngo I would need to define this for each folder right? Is there a solution to define it once and use it all along the road? And what should be inside tsconfig.app.json in the solution you have provided?
Yes. You could for 1 parent folder too like "src/*": ["src/app/*"]
@TomaszSmykowski so did my answer help you ? If so please vote up and mark my answer as accepted.
|

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.