簡體   English   中英

tsconfig.json 僅在某些時候尊重 baseUrl 絕對導入

[英]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導入ButtonCard.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'

我花了幾個小時研究類似的情況,並與許多組合試驗baseUrlinclude和其他tsconfig.json配置,但無法弄清楚什么是錯的! 感謝您的幫助。

我的猜測是您的tsconfig.json結構不正確(根據您的示例,您做得不對,或者您沒有發布整個tsconfig.json文件)或者它不在正確的位置。

  1. tsconfig.json放在項目的根文件夾中(與package.json相同)
  2. 確保您的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM