我正在尝试使用 Barrels 和 tsconfigs
paths
选项导入一些服务,但我无法让 Angular 和 vscode 相处。
如果它对一个有效,则对另一个无效,反之亦然......
我的情况似乎很简单:
src/app/services
我有一个在index.ts中导出的服务src/tsconfig.app.json
就是这样:{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": [],
"baseUrl": ".",
"paths": {
"services": ["app/services"]
}
},
"exclude": [
"test.ts",
"**/*.spec.ts"
],
}
并且 我的 Angular 应用程序编译没有问题,但是每次我尝试从
'services'
导入我的服务时,vscode 总是给我错误,给我 [ts] Cannot find module 'services'.
为什么?
我使用的是 typescript 3.1.6,在 vscode 设置中我有
"typescript.tsdk": "C:/Users/myuser/AppData/Roaming/npm/node_modules/typescript/lib"
(我也尝试保留默认设置,没有更改)
编辑:
如果我从
paths
开始在 ./tsconfig.json
中指定 src
,vscode 会很高兴,但 Angular 却不会。
如果我在
paths
和 tsconfig.json
中指定 src/tsconfig.app.json
,vscode 和 Angular 都很高兴,但对我来说这似乎是一个太愚蠢的解决方法......
我想通了,即使我一直认为那是荒谬的......
VsCode 会自动查找
tsconfig.json
文件,它并不关心 tsconfig.app.json
,因此需要在 paths
中指定 tsconfig.json
。
同时,Angular-cli脚手架在
baseUrl
中指定了一个tsconfig.app.json
参数,它会覆盖上面的参数。
解决方案是删除
baseUrl
中的tsconfig.app.json
参数或将其值编辑为"../"
(作为个人评论,鉴于 VSCode 主要用于构建 Angular 解决方案,我认为应该在 Angular-CLI 脚手架或 VSCode 如何查找 tsconfig 文件中重新审视一些内容)
看起来 VSCode 仅直接检查
tsconfig.json
在你打开的文件夹中。它不会像 tsc 那样检查上面的文件夹,也不会查看 tsconfig.app.json
。因此,在某些情况下,
baseUrl
可能会丢失,因为 VSCode 根本没有读取
tsconfig.json
。VSCode 对固定位置单个
tsconfig.json
的限制已经存在了一段时间,似乎要使其更加灵活并不容易:https://github.com/microsoft/vscode/issues/12463 (滚动到最后) 如上所述,这在具有多个子项目的 Angular-CLI 脚手架中很烦人,其中工作区根部只有一个
tsconfig.json
。显然,这些项目的
baseUrls
中可能有不同的
tsconfig.app.json
,它们不能全部放在根部的单个
tsconfig.json
中。作为一种解决方法,除了
baseUrl
中的项目特定
tsconfig.app.json
之外,我还使用
tsconfig.json
在子项目的 src 文件夹中为 VSCode 创建了一个额外的最小
"baseUrl":"."
,并从那里打开 VSCode。我还没有对此进行严格的测试,但到目前为止 Angular 编译和 VSCode 智能感知似乎都很满意。
baseUrl
和
paths
放在
tsconfig.json
中,而不是
tsconfig.app.json
。
tsconfig.json
处创建
tsconfig.app.json
。
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "./",
"paths": {
/* your_paths */
}
}
}
tsconfig.app.json
和
tsconfig.spec.json
中重写
"extends": "./tsconfig.json"
最终文件结构
projects
your_application
tsconfig.json
tsconfig.spec.json
tsconfig.app.json
tsconfig.json
['**/*']
- 当您覆盖它时只需将 '**/*' 添加到包含的路径中。 这是我的问题,但很难检测到包含导致了这个问题。
tsconfig.json
,然后扩展我的示例中的其他 tsconfig,它是
tsconfig.lib.json
,所以我的
tsconfig.json
是
//!for vscode to detect other tsconfigs paths
{
"extends": "./tsconfig.lib.json",
}
注意:我必须退出 Vscode(在 mac 中为 cmd+q
)并重新打开它才能生效