最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJS: Converting index.js to index.tsx - Module not found: Error: Can't resolve '.App' -

programmeradmin0浏览0评论

I'm trying to add some pages in typescript, and since I can only import .ts files in .ts or .tsx files, I renamed "Index.js" to "Index.tsx" and "App.js" to "App.tsx".

Now I'm getting the following error:

ERROR in ./src/index.tsx 7:0-24
Module not found: Error: Can't resolve './App'

Index.tsx

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

App.tsx

function App() {
  return (
    <Provider store={store}>
      <div>hi</div>
    </Provider>
  );
}

export default App;

Why can't Index.tsx resolve App.tsx? I created the project with create-react-app and I'm using React 17.0.2.

I'm trying to add some pages in typescript, and since I can only import .ts files in .ts or .tsx files, I renamed "Index.js" to "Index.tsx" and "App.js" to "App.tsx".

Now I'm getting the following error:

ERROR in ./src/index.tsx 7:0-24
Module not found: Error: Can't resolve './App'

Index.tsx

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

App.tsx

function App() {
  return (
    <Provider store={store}>
      <div>hi</div>
    </Provider>
  );
}

export default App;

Why can't Index.tsx resolve App.tsx? I created the project with create-react-app and I'm using React 17.0.2.

Share Improve this question asked Dec 26, 2021 at 14:37 SJ19SJ19 2,12310 gold badges39 silver badges80 bronze badges 1
  • 1 Does this answer your question? React: Can't import .tsx file – pilchard Commented Dec 26, 2021 at 14:48
Add a ment  | 

2 Answers 2

Reset to default 2

1: Create file tsconfig.json in the src directory.

paste this code.

{
  "pilerOptions": {
    "target": "ES6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

2: install npm I cra-template-typescript

3: import App from './App.tsx'; instead of import App from './App';

That's because webpack config in CRA is not set up for typeScript.

If you wanna use typeScript in your React project, you should begin with "CRA typescript template"!

install CRA typeScript template and then make code in there.

the template npm site is here https://www.npmjs./package/cra-template-typescript

I hope you find an answer :D

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论