Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import .tsx file from .ts file (and vice versa)

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 { /*...*/ }

Now TypeScript tells me

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

So I tried this:

src/index.ts

import WriteEditor from './write_editor.tsx';

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.

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.

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

like image 239
Lukas Avatar asked Jan 15 '18 22:01

Lukas


People also ask

Can t import tsx?

The error "An import path cannot end with a '. tsx' extension" occurs when we include the extension when importing TypeScript files in a React. js application. To solve the error, remove the extension from your TypeScript imports.

Is TSX same as TS?

The . ts file extension is used when you are creating functions, classes, reducers, etc. that do not require the use of JSX syntax and elements, whereas the . tsx file extension is used when you create a React component and use JSX elements and syntax.

What is TSX file type?

A TSX file is a TypeScript (. TS) file written using JSX syntax. It contains code that is most likely part of a single-page or mobile application. TSX files can be opened in any text editor, but are meant to be opened in source code editors.


1 Answers

When you write

import WriteEditor from './write_editor';

Webpack will automatically look for

  • ./write_editor
  • ./write_editor.js
  • ./write_editor.json
  • (And a few others)

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"],
  },
}
like image 107
loganfsmyth Avatar answered Sep 19 '22 07:09

loganfsmyth