ZeroSevenTen
ZeroSevenTen

Reputation: 1504

React: Can't import .tsx file

New to using TypeScript with React. When I import a component that is from a .tsx file, it assumes it is a .js file by default. The error says that there is no About.js file or Contact.js file in that directory. Additionally, the TS linter won't let me add .tsx to the end of the file path. How to fix this? I used 'npx create-react-app project_name --typescript'. Here is my code

import React from 'react'
import { BrowserRouter, Route } from 'react-router-dom'
import Home from './views/Home'
import About from './views/About'
import Contact from './views/Contact'
import Navbar from './components/Navbar'
import Footer from './components/Footer'

const App: React.FC<{}> = () => {
  return (
    <BrowserRouter>
      <Navbar title="Website" links={['About', 'Contact']} color="blue"/>

      <Route exact path="/" component={Home}/>
      <Route path="/home" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/contact" component={Contact}/>

      <Footer/>
    </BrowserRouter>
  )
}

export default App

Upvotes: 15

Views: 26528

Answers (3)

Orit
Orit

Reputation: 343

I had the same problem, I used the default create app of react (that create a JS project by default).

  1. A temporary solution I used was to add the tsx extension to the import, it compiles and the site works but appears like a compilation error in the IDE
  2. The permanent solution was to create a new react app using the typescript template like so:

npx create-react-app --template typescript

Upvotes: 2

mukara
mukara

Reputation: 7

npm install --save-dev webpack-cli

Upvotes: -2

Idin Khayami
Idin Khayami

Reputation: 252

Did you use create react app? In case you didn't use or used and eject it you should add this config to your webpack config file:

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

In case that you used create react app and didn't eject it you can add these rules to your typescript-eslint

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

Upvotes: 9

Related Questions