简体   繁体   English

如何在反应中正确导入和导出模块 typescript

[英]how to correctly import and export modules in react typescript

I am having trouble with some basic module importing and exporting in react typescript. Exporting as follows:我在 react typescript 中导入和导出一些基本模块时遇到问题。导出如下:

//gameStateReducer.ts
import { Action, ActionKind, GameState } from './types';

export const gameStateReducer = (
  gameState: GameState,
  action: Action
): GameState => {

  //yada yada yada
};

and importing as:并导入为:

//index.tsx
import { gameStateReducer } from './gameStateReducer';

The error message is:错误信息是:

Compiled with problems:

ERROR in ./src/index.tsx 9:0-54

Module not found: Error: Can't resolve './gameStateReducer' in '/Users/REDACTED/Documents/development/react-js/wordle/src'

This was all working when I was developing the same project on stackblitz, but trouble came when I began working locally with create-react-app.当我在 stackblitz 上开发同一个项目时,这一切都有效,但当我开始在本地使用 create-react-app 时,麻烦来了。

I'm having the same problem with my constants module.我的常量模块也有同样的问题。

I've read typescript's reference page on exports and imports, and as a matter of fact, my types and interfaces are importing and exporting just fine.我已经阅读了关于导出和导入的打字稿参考页面,事实上,我的类型和接口导入和导出都很好。

I've tried importing and exporting to default with no luck.我试过导入和导出默认值,但没有成功。

Gotta be something simple I'm missing here.一定是我在这里缺少的简单东西。 Thanks!谢谢!

The way you added import this should work.您添加import this 的方式应该有效。 I hope your directory structure is like我希望你的目录结构是这样的

src来源

  • gameStateReducer.ts gameStateReducer.ts
  • index.ts索引.ts

if your gameStateReducer.ts is under different directory then you should update import path to that directory.如果您的gameStateReducer.ts在不同的目录下,那么您应该更新该目录的导入路径。

for example, if you have structure like below例如,如果你有如下结构

src来源

  • anotherDirectory -> gameStateReducer.ts另一个目录 -> gameStateReducer.ts
  • index.ts索引.ts

then update import statement to this然后import语句更新为此

import { gameStateReducer } from './anotherDirectory/gameStateReducer';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM