问题描述
我正在处理一个 Angular 项目。我有一个图书馆 tools
和一个项目 example
。我的项目结构是这样的(Monorepo)
root
|-- projects
| |-- example
| | |-- src
| | | `-- app
| | | |-- app.module.ts
| | | `-- view
| | | `-- main.component.ts
| | `-- tsconfig.app.json
| `-- tools
`-- tsconfig.json
我的tsconfig.json
看起来像这样
{
"compileOnSave": false,"compilerOptions": {
"baseUrl": "./","outDir": "./dist/out-tsc","forceConsistentCasingInFileNames": true,"strict": false,"noImplicitReturns": false,"noFallthroughCasesInSwitch": true,"sourceMap": true,"declaration": false,"downlevelIteration": true,"experimentalDecorators": true,"moduleResolution": "node","importHelpers": true,"target": "es2015","module": "ES2020","lib": [
"es2018","dom"
]
}
}
还有我的tsconfig.app.json
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "../../tsconfig.json","compilerOptions": {
"outDir": "../../out-tsc/app","types": [],"allowJs": true,"traceResolution": true,"paths": {
"tools": [
"dist/tools/tools","dist/tools"
],"@example/*": [
"projects/example/src/app/*","projects/example/src/app/view/features/*","projects/example/src/app/core/guards/index.ts","projects/example/src/app/core/components/index.ts","projects/example/src/app/core/model/index.ts","projects/example/src/app/core/services/index.ts","projects/example/src/app/view/features/f1/store/index.ts","projects/example/src/app/view/features/f2/store/index.ts","projects/example/src/app/view/features/f3/store/index.ts"
]
}
},"files": [
"src/main.ts","src/polyfills.ts"
],"include": [
"src/**/*.d.ts"
]
}
当我尝试在我的 tools
中导入 app.module.ts
时,它工作正常。但是当我在任何功能/子模块中导入它时,比如 main.component.ts
,IntelliJ 将其标记为错误。
TS2307: Cannot find module 'tools' or its corresponding type declarations
我尝试在命令行中运行 tsc --project projects/example/tsconfig.app.json
并检查输出,我发现它已成功解决
Module name 'tools' was successfully resolved
我一无所知,没有解决方案!
解决方法
尝试将您的路径配置移动到根 tsconfig.json 而不是特定于项目的 tsconfig.app.json。这实际上是 Angular CLI 库原理图 (ng g lib tools
) 添加它们的地方。
要显示特定文件的类型信息,IntelliJ 将读取该文件“属于”的 tsconfig。这由 "files"
/"include"
/"exclude"
键决定:
- 您的 tsconfig.app.json 当前配置为包含
main.ts
和polyfills.ts
(以及它们引用的任何文件),或任何*.d.ts
。 - 您的 tsconfig.json 将充当任何其他文件的全部内容。
现在,app.module.ts
被 main.ts
引用,因此它是 tsconfig.app.json 的一部分。因此,在该文件中,IntelliJ 知道路径映射,并且 tools
导入工作正常。
但是,如果您正确地进行了延迟路由,则 main.component.ts
很可能不会由 main.ts
直接导入。它现在被认为是 tsconfig.json 的一部分,NOT tsconfig.app.json。因此,在该文件中,IntelliJ 不知道路径映射,tools
导入抛出。
(作为一个小测试,尝试将 main.component.ts
导入 app.module.ts
。tools
导入应该立即开始在 main.component.ts
中工作。)
当在 tsconfig.json 中声明时,路径适用于任何文件,因为 tsconfig.app.json 扩展了它。
旁注:您实际上可以查看 IntelliJ 用于任何特定文件的 tsconfig。单击底部状态栏中的 TypeScript
按钮,然后单击编译。您应该会看到您当前正在查看的文件,以及该文件所属的 tsconfig。 Screenshot.
您是否尝试过删除 .project .settings .classpath 文件夹?我的 gradle 项目有类似的东西。
rm -rf .project .settings .classpath
然后我也尝试在这之后打开设置>无效缓存并重新启动
最后一种情况我还必须再次克隆和导入项目,然后执行上述操作。
试试看,Intellij 在构建/编译时总是会产生很多垃圾。