【问题标题】:tsconfig.json honoring baseUrl absolute imports only some of the timetsconfig.json 仅在某些时候尊重 baseUrl 绝对导入
【发布时间】:2021-09-23 19:50:02
【问题描述】:

我的create-react-app一些 文件中尊重绝对导入,但在其他文件中则不然。

文件夹结构

.
+-- tsconfig.js
+-- package.json
+-- src
|   +-- components
|   |   +-- ui
|   |   |   +-- Button
|   |   |   |  +-- Button.tsx
|   |   |   +-- Card
|   |   |   |  +-- Card.tsx
|   +-- pages
|   |   +-- Home.tsx
|   +-- index.tsx

tsconfig.json


{
  "baseUrl": "src",
  "include": [ "src/**/*" ],
}

如果我从Home.tsx 文件中导入Button,它将按预期工作:

Home.tsx

import Button from 'components/ui/Button/Button.tsx'
console.log(Button)

Button正常登录控制台。)

Card.tsx

但是,如果我尝试从 Card.tsx 导入 Button,则会出错。

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 配置的多种组合,但无法找出问题所在!感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs typescript package.json tsconfig


    【解决方案1】:

    我的猜测是您的 tsconfig.json 结构不正确(根据您的示例,您没有正确执行或未发布 whle tsconfig.json 文件)或者它不在正确的位置。

    1. tsconfig.json放到你项目的根目录下(和package.json一样)
    2. 确保您的tsconfig.json 结构如下:

    tsconfig.json

    {
      "compilerOptions": {
        "baseUrl": "src",
        ...
      },
      "include": ["src"]
    }
    

    注意"include"的位置。和"baseUrl"不在一个级别

    这是我根据您项目的文件夹/文件结构为您制作的working demo

    注意:最后一件事。 linter 警告我 An import path cannot end with a '.tsx' extension. Consider importing 'components/ui/Card/Card' instead.ts(2691)... 这意味着您也应该从导入路径中删除 .tsx 扩展名。

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 2012-02-11
      • 2015-10-04
      • 2020-09-14
      • 2018-02-19
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多