问题描述
我有一个包含.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
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
,因此您需要告诉它也使用 resolve.extensions
:
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文件(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!