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?

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
Tom Smykowski
  • 25,487
  • 54
  • 159
  • 236

1 Answers1

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';
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
  • 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` – JohnnyDevNull Jul 03 '19 at 08:05
  • @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? – Tom Smykowski Jul 03 '19 at 10:10
  • @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? – Tom Smykowski Jul 03 '19 at 10:11
  • 1
    Yes. You could for 1 parent folder too like `"src/*": ["src/app/*"]` – Tony Ngo Jul 03 '19 at 10:18
  • @TomaszSmykowski so did my answer help you ? If so please vote up and mark my answer as accepted. – Tony Ngo Jul 03 '19 at 15:44
  • @TonyNgo I can vote up, but this is not the final solution. Final solution is more from a comment of NileshMali (not entirely but from this the solution came) – Tom Smykowski Jul 04 '19 at 16:44