Search code examples
angularvisual-studio-codetsconfig

How do I properly set up a path in tsconfig.ts?


I'm working on a project and I'd like to be able to set a custom path for quicker access but I keep getting the error "Cannot find module @env/environment".

This is my path: Path config

{ 
 "compileOnSave": false,
 "compilerOptions": {
 "baseUrl": "./",
 "paths": {
   "@env/*": ["./src/environments/*"],
   "@core/*": ["./src/app/@core/*"]
 },
 "outDir": "./dist/out-tsc",
 .
 .
 .

When I try importing it in a component, it doesn't find it. Am I doing something wrong?

This is my current set-up:

Angular CLI: 8.3.26 Node: 12.16.1 OS: darwin x64 Angular: 8.2.14

Visual Studio Code: 1.44.2


Solution

  • Please do it like this

    "paths": {
       "@env/*": ["src/environments/*"],
       "@core/*": ["src/app/@core/*"]
     },
    

    you do not need ./ here as you are specifying ./ in your base url

    Have in mind that the path where you want to refer to, it takes your baseUrl as the base of the route you are pointing to and it's mandatory as described on the doc.

    The character '@' is not mandatory.

    After you set it up on that way, you can easily use it like this:

    import { Yo } from '@core/index';
    

    the only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.

    also you can check this example

    https://github.com/ialex90/TypeScript-Node-Starter/commit/a4e8cc1f8f8d5176e0099e05b51f97b0ef4bebea