Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

paths is not working in tsconfig.app.json as expected

I am using Angular to develop my website. And I wanna set a BASE_API for my project depends on prod or dev. Therefore, I add some code in environment

  export const environment = {
    production: true,
    BASE_API: 'http://localhost:3000/',
  };

And I wanna use import { environment } from '@environments/environment' to import instead of import { environment } from '../../../environments/environment'; So I set tsconfig.app.json just like below

  {
    "extends": "../tsconfig.json",
    "compilerOptions": {
      "outDir": "../out-tsc/app",
      "module": "es2015",
      "baseUrl": "./",
      "paths": {
        "@angular/*": [
          "../node_modules/@angular/*"
        ],
        "@environments/*": [
          "../src/environments/*"
        ]
      }
    },
  }

And my project structure as below

 src
    app
    environments
            environment.prod.ts
            environment.ts

However, the VSCode shows:

ERROR in src/app/user/article/article.service.ts(3,29): error TS2307: Cannot find module '@environments/environment'.

How can I fix this problem?

like image 746
Eve-Sama Avatar asked Mar 18 '19 04:03

Eve-Sama


1 Answers

This is called alias. Aliasing our app and environments folders will enable us to implement clean imports which will be consistent throughout our application.

To be able to use aliases you have to add baseUrl and paths properties to tsconfig.json file.

So here in your code, just change your baseUrl to src

 {
    "extends": "../tsconfig.json",
    "compilerOptions": {
      "outDir": "../out-tsc/app",
      "module": "es2015",
      "baseUrl": "src",
      "paths": {
         "@app/*": ["app/*"],
         "@environments/*": ["environments/*"]
       }
    }
  }

Now you can import environment file like:

import { environment } from '@environments/environment
like image 187
Surjeet Bhadauriya Avatar answered Nov 15 '22 03:11

Surjeet Bhadauriya