【问题标题】:Converting grouped React components to typescript将分组的 React 组件转换为打字稿
【发布时间】:2020-10-30 03:36:57
【问题描述】:

我正在将我的 react 项目转换为使用 typescript。这是我原始 js 项目的文件结构的示例(简化版):

    • 组件
      • index.js
      • 输入
        • button.js
        • textbox.js
        • checkbox.js
        • index.js
      • 小部件
        • index.js
        • widget1.js
        • widget2.js

我的 src/components/inputs/index.js 看起来像这样:

export { InputButton as Button } from './button'
export { InputTextbox as Textbox } from './textbox'
export { InputCheckbox as Checkbox } from './checkbox'

(src/components/widgets/index.js) 格式相同

我的 src/components/index.js 看起来像

export { Button, Textbox, Checkbox} from './inputs'
export { Widget1, Widget2} from './widgets'

我为 src/components/ 设置了一个别名路径,以便我现在可以像这样导入组件:

import {Button} from "@components"

在我开始使用打字稿之前,这一切都很好。

我现在正在尝试将此项目转换为打字稿。我已将我的组件转换为 .tsx 并为它们添加了接口。但是,当我尝试使用 import {Button} from "@components" 导入 Button 时,我的导入语句的“@componets”部分在我的 ide (vscode) 中带有下划线,并且出现以下错误:

Could not find a declaration file for module '@components'. '/myProject/src/components/index.js' implicitly has an 'any' type.

我认为问题可能是我缺少一个“index.d.ts”文件,但我不确定它的内容是什么。

不使用 create-react-app。

提前谢谢你。

【问题讨论】:

  • 你的 react 应用是使用 create-react-app 创建的吗?
  • 应该提到这一点。不,它不是用 create-react-app 引导的
  • 看起来您的路径别名解析为文件的 JavaScript 版本,而不是新的 TypeScript 版本。您能否添加与路径别名有关的 webpack 配置和 tsconfig.json 位?另外,请确保新的 .tsx 文件旁边没有同名的 .js 文件!

标签: reactjs typescript


【解决方案1】:

您还需要为 TypeScript 设置一个类似的路径别名,我认为 this article explains 很好地做到这一点,比我在几行中做的更好:)

Alternativelu 您可以在TypeScript docs 中阅读有关paths 的更多信息

【讨论】:

  • @MarkDavid 对不起,我看错了错误信息!我将编辑我的答案
猜你喜欢
  • 2020-12-27
  • 2018-06-14
  • 2018-11-10
  • 2018-04-26
  • 2020-02-16
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2019-04-03
相关资源
最近更新 更多