Angular 7 Can't find a way to get tsconfig.json path mapping works

大憨熊 提交于 2020-12-28 21:00:12

问题


I've started an angular 7 project and I'm trying to configure the "path mapping" on angular.json to change my import way from this:

import { environment } from '../../../environments/environment';

to this:

import { environment } from '@environments/environment';

I've done this config on the root level tsconfig.json file:

"compilerOptions": {
        "baseUrl": "src", // This must be specified if "paths" is.
         ...
        "paths": {
            "@app/*": ["app/*"],
            "@config/*": ["app/_config/*"],
            "@environments/*": ["environments/*"],
            "@shared/*": ["app/_shared/*"],
            "@helpers/*": ["helpers/*"]
        },
...

But I also get this error on the cli

ERROR in src/app/errors/not-foud/not-found.component.ts(2,29): error TS2307: Cannot find module '@environments/environment'

Is there something I'm missing?


回答1:


After trying and trying again I find out that the problem was with one of my vscode setting that was called:"Typescript > Preferences: Import Module Specifier" that was set to "relative", instead of "non-relative". Changing this, I was able to solve the problem.




回答2:


Tested with angular 9 RC:

update both place:

at project base level to make vscode happy:

// tsconfig.json
// .\
{
  ...
   "paths": {
      "@x/*": [
        "x/*"
      ],
      "@web-env/*": [
        "src/environments/*"
      ],
      "@web-app/*": [
        "./projects/web/src/app/*"
      ],
    }
  ...
}

inside child project, update this to make cli happy:

// app.tsconfig.json
// .\projects\web\tsconfig.app.json
{
  ...
  "baseUrl": "./",
  "paths": {
    "@web-env/*": [
      "src/environments/*"
    ],
    "@web-app/*": [
      "src/app/*"
    ],
  }
  ...
}



回答3:


In my case it was because the src\tsconfig.app.json also had a paths map defined. The one in my main tsconfig was being ignored by the TypeScript compiler. I removed that and it started working.



来源:https://stackoverflow.com/questions/54831406/angular-7-cant-find-a-way-to-get-tsconfig-json-path-mapping-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!