简体   繁体   English

反应:无法导入 .tsx 文件

[英]React: Can't import .tsx file

New to using TypeScript with React.刚开始使用 TypeScript 和 React。 When I import a component that is from a.tsx file, it assumes it is a.js file by default.当我导入一个来自 .tsx 文件的组件时,默认情况下它假定它是一个 .js 文件。 The error says that there is no About.js file or Contact.js file in that directory.该错误表明该目录中没有 About.js 文件或 Contact.js 文件。 Additionally, the TS linter won't let me add.tsx to the end of the file path.此外,TS linter 不允许我将 add.tsx 添加到文件路径的末尾。 How to fix this?如何解决这个问题? I used 'npx create-react-app project_name --typescript'.我使用了“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

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:如果您没有使用或使用并弹出它,您应该将此配置添加到您的 webpack 配置文件中:

{
  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如果您使用 create react app 并且没有弹出它,您可以将这些规则添加到您typescript-eslint

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

I had the same problem, I used the default create app of react (that create a JS project by default).我有同样的问题,我使用默认的反应创建应用程序(默认创建一个 JS 项目)。

  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我使用的一个临时解决方案是将 tsx 扩展名添加到导入中,它可以编译并且站点可以正常工作,但在 IDE 中看起来像是一个编译错误
  2. The permanent solution was to create a new react app using the typescript template like so:永久解决方案是使用 typescript 模板创建一个新的 React 应用程序,如下所示:

npx create-react-app --template typescript npx create-react-app --template typescript

npm install --save-dev webpack-cli

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM