在tsconfig.app.json中为角度项目定义路径

在tsconfig.app.json中为角度项目定义路径

问题描述:

该项目是通过角度CLI生成的。我有以下文件夹结构:在tsconfig.app.json中为角度项目定义路径

enter image description here

我想在tsconfig.app.json定义为酒吧文件夹的路径,并导入到CarGarage

tsconfig.app.json

{ 
    "extends": "../tsconfig.json", 
    "compilerOptions": { 
    ... 
    "baseUrl": "./", 
    "paths" : { 
     "@bar" : ["foo/bar"] 
    }, 
    ... 
    }, 
    ... 
} 

Garage.ts

import { Car } from "@bar/Car"; 
export class Garage {} 

在garage.ts我有一个错误:

Cannot find module '@bar/car'.

+0

你会发现[这篇文章](https://blog.angularindepth.com/configuring-typescript-compiler-a84ed8f87e3#06ea)有帮助,它解释了如何以及为什么使用'路径'相当精心 –

+0

@ AngularInDepth.com , 谢谢你,先生。我简要介绍了这篇文章,但仍然没有得到它。您能否提供一些关于为什么在该特定示例中无法解决“Car”模块的见解? – koryakinp

+0

我已发布[我的回答](https://*.com/a/46640069/2545680) –

您需要定义paths这样的:

"paths" : { 
     "@bar/*" : [ 
      "foo/bar/*" 
     ] 
    }, 

欲了解更多信息,请阅读

+0

谢谢先生,它解决了原来的问题,但编辑器(在我的情况下VS代码)仍抱怨'[ts]无法找到模块'@ bar/Car'。' – koryakinp

+0

@koryakinp,对不起,我不熟悉VSCode。考虑单独提问 –

+0

路径本身的尾部*(foo/bar/*)是我的情况的症结所在。 – treeno

我认为这可能工作

{ 
    "extends": "../tsconfig.json", 
    "compilerOptions": { 
    ... 
    "baseUrl": "./", 
    "paths" : { 
     "@bar" : ["foo/bar"], 
     "@environment/*": ["environments/*"], 
     "@shared/*": ["app/_shared/*"], 
     "@helpers/*": ["helpers/*"] 
     //you can define multiple paths inside this 
    }, 
    ... 
    }, 
    ... 
} 

,问题看起来像重复question

+0

对不起,它实际上是''路径“:{”@bar“:[”foo/bar“]}, ' – koryakinp

+0

编辑我的代码,以提供额外的细节@ koryakinp – Vignesh