7

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?

5
  • 1
    Your question mentions write_editor.jsx and write_editor.tsx. Why do you have a .jsx file? Commented Jan 15, 2018 at 22:14
  • Oh sorry that is a typo, it's all tsx Commented Jan 15, 2018 at 22:47
  • Have you configured Webpack to auto-append the .ts and .tsx extensions? Commented Jan 15, 2018 at 22:49
  • I did, this is my webpack config gist.github.com/LukasBombach/38b5b1f19da819e6f4effee743162c6d Commented Jan 15, 2018 at 22:56
  • Oh wait, what do you mean with auto-append? Commented Jan 15, 2018 at 23:00

3 Answers 3

23

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"],
  },
}
Sign up to request clarification or add additional context in comments.

Comments

7

In my case, I got same error when using typescript-eslint. It is an app created by create-react-app.

The way is by adding this code in .eslintrc.js.

module.exports = {
  // ...
  settings: {
    'import/resolver': {
      'node': {
        'extensions': ['.js','.jsx','.ts','.tsx']
      }
    }
  }
};

Comments

0

In my case I had renamed a .jsx file to .tsx and had to delete Parcel's cache to get it to resolve.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.