【问题标题】:React does not allow importing types from external folders (React + TypeScript)React 不允许从外部文件夹导入类型(React + TypeScript)
【发布时间】:2022-07-09 07:20:57
【问题描述】:

我有一个带有 TypeScript 的 React 项目。我正在尝试从外部文件夹导入类型 - 在 React 文件夹之外。然而,React 似乎不允许这样做。我在 CRA 之上使用 craco 来运行应用程序。

项目:https://github.com/accord-dot-app/app

types/
- ...
- deps.types.ts

frontend/
- ...
- src/
-- index.tsx

类型/deps.types.ts:

// ... imports

export interface Deps {
...
}

前端/src/index.tsx:

import { Deps } from '.../deps.types.ts';

...

这是我在运行craco start 时遇到的错误。

File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
| import ChannelLeave from '@accord/backend/ws/ws-events/channel-leave';
|
> declare interface Deps {
|   channels: Channels;
|   /** @deprecated */

如果我注释掉这些行,我只会在另一个类似类型的文件中得到另一个错误。

如何消除错误?

【问题讨论】:

  • React 强加这种行为有点烦人,但您可以通过将 types 文件夹转换为本地 npm 包,然后将 install 从您的 React 项目中转换为它来克服它。 This question 有点相关。让我知道这是否对您有用,并且您希望我将其组合成答案。
  • 我已经这样做了,它安装为file:../types,然后导入为@accord/types。这会在 node_modules/ 文件夹中创建指向 ../types 的符号链接。也许符号链接是导致 React 认为它是一个外部文件夹的原因——即使它位于 node_modules/ 中。
  • 你也可以做相反的事情:将类型文件存储在你的 React src 目录中,然后从其他外部模块导入它/将其符号链接到 React 不会关心的外部位置。
  • 到目前为止,这已经奏效,但应该避免将特定目录排除在类型检查之外。我尝试了另一种解决方案,但无法使用我的设置:stackoverflow.com/questions/44114436/…

标签: javascript reactjs typescript webpack


【解决方案1】:

尝试使用:

const C1: React.FC<CProps> = (props) => { }

代替:

const C2 = (props: CProps) => {};

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2016-11-15
    • 2020-12-14
    • 2017-11-09
    • 2020-04-10
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多