[英]tsconfig.json honoring baseUrl absolute imports only some of the time
我的create-react-app
在某些文件中支持絕對導入,但在其他文件中不支持。
.
+-- tsconfig.js
+-- package.json
+-- src
| +-- components
| | +-- ui
| | | +-- Button
| | | | +-- Button.tsx
| | | +-- Card
| | | | +-- Card.tsx
| +-- pages
| | +-- Home.tsx
| +-- index.tsx
{
"baseUrl": "src",
"include": [ "src/**/*" ],
}
如果我從Home.tsx
文件導入一個Button
,它會按預期工作:
主頁.tsx
import Button from 'components/ui/Button/Button.tsx'
console.log(Button)
( Button
正常登錄控制台。)
卡片.tsx
但是,如果我嘗試從Card.tsx
導入Button
, Card.tsx
出錯。
import Button from 'components/ui/Button/Button.tsx'
console.log(Button)
FAIL Failed to compile
./src/components/ui/Card/Card.tsx
Module not found: Can't resolve 'components' in '/Users/ninja/Desktop/Projects/My Apps/app-one/src/components/ui/Card/Card.tsx'
我花了幾個小時研究類似的情況,並與許多組合試驗baseUrl
, include
和其他tsconfig.json
配置,但無法弄清楚什么是錯的! 感謝您的幫助。
我的猜測是您的tsconfig.json
結構不正確(根據您的示例,您做得不對,或者您沒有發布整個tsconfig.json
文件)或者它不在正確的位置。
tsconfig.json
放在項目的根文件夾中(與package.json
相同)tsconfig.json
結構如下:配置文件
{
"compilerOptions": {
"baseUrl": "src",
...
},
"include": ["src"]
}
注意"include"
的位置。 它與"baseUrl"
不在同一級別
這是我根據您項目的文件夾/文件結構為您制作的工作演示。
注意:最后一件事。 An import path cannot end with a '.tsx' extension. Consider importing 'components/ui/Card/Card' instead.ts(2691)
警告我, An import path cannot end with a '.tsx' extension. Consider importing 'components/ui/Card/Card' instead.ts(2691)
An import path cannot end with a '.tsx' extension. Consider importing 'components/ui/Card/Card' instead.ts(2691)
.tsx
An import path cannot end with a '.tsx' extension. Consider importing 'components/ui/Card/Card' instead.ts(2691)
... 這意味着您也應該從導入路徑中刪除.tsx
擴展名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.