无法从.ts文件导入.tsx文件(反之亦然) [英] Cannot import .tsx file from .ts file (and vice versa)

查看:1797
本文介绍了无法从.ts文件导入.tsx文件(反之亦然)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含.ts.tsx文件的项目,我正尝试从.ts文件导入.tsx文件,如下所示:

I have a project with .ts and .tsx files and I am trying to import a .tsx file from a .ts file, like so:

src/index.ts

import WriteEditor from './write_editor';

src/write_editor.tsx

import Events from './events';
import Actions from './actions';

export default class WriteEditor extends React.Component { /*...*/ }

现在TypeScript告诉我

Now TypeScript tells me

./src/index.ts中的

错误 找不到模块:错误:无法解析'/Users/luke/Projekte/writejs/code/writejs/src'中的'./write_editor' @ ./src/index.ts 3:23-48 @ multi ./src/index.ts

ERROR in ./src/index.ts Module not found: Error: Can't resolve './write_editor' in '/Users/luke/Projekte/writejs/code/writejs/src' @ ./src/index.ts 3:23-48 @ multi ./src/index.ts

所以我尝试了这个:

src/index.ts

import WriteEditor from './write_editor.tsx';

现在我的IDE告诉我不要编写扩展名tsx,并且在 src/write_editor.tsx 中出现错误,因为TypeScript无法从.tsx文件中找到我的.ts文件.

Now my IDE tells me not to write the extensions tsx and I get an errors in src/write_editor.tsx because TypeScript cannot find my .ts files from a .tsx file.

然后我去重命名导入并添加了.ts扩展名

Then I went to rename the imports and added the .ts extensions

import Events from './events.ts';
import Actions from './actions.ts';

现在,我遇到了很多麻烦或错误,告诉我根本不要编写扩展名.

Now I am getting tons or errors telling me not to write extensions at all.

那么我们如何从ts导入tsx,反之亦然?

So how can we import tsx from ts and vice versa?

推荐答案

撰写时

import WriteEditor from './write_editor';

Webpack会自动寻找

Webpack will automatically look for

  • ./write_editor
  • ./write_editor.js
  • ./write_editor.json
  • (还有其他几个人)
  • ./write_editor
  • ./write_editor.js
  • ./write_editor.json
  • (And a few others)

由于您使用的是.ts.tsx,因此您需要告诉它也使用

Since you're using .ts and .tsx, you need to tell it to look for those too in your Webpack config using resolve.extensions:

{
  resolve: {
    extensions: [".js", ".json", ".ts", ".tsx"],
  },
}

这篇关于无法从.ts文件导入.tsx文件(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆