【发布时间】: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