Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React can't resolve .tsx files

I made a new react project using npx create-react-app app-name --template typescript and it ran fine until I imported another .tsx file. Now when I try to import another .tsx file it gives me an error: Module not found: Error: Can't resolve './components/component' in '/Users/benbaldwin/Desktop/project/frontend/teacher/src'

The only thing I'm doing differently than normal is the file structure. Since I have multiple react projects in the frontend folder that share dependancies I moved the node_modules to cover all of those subdirectories. my file structure looks like this:

- frontend
  - node_modules
  - project-1
      - public
      - src
        index.tsx
        react-app-env.d.ts
        - components
          component.tsx
  - project-2
  package.json
  tsconfig.json

the component file looks like this:

import React from 'react';

const Component: React.FC = () => {
    return <div>hello</div>;
};

export default Component;

and the index file looks like this:

import React from 'react';
import ReactDOM from 'react-dom';
import Component from './components/component';
import './index.css';

ReactDOM.render(
    <React.StrictMode>
        <Component />
    </React.StrictMode>,
    document.querySelector('#root')
);

do I need to eject create-react-app and write out my own web pack config or is there a better way to fix this?

the full source code is on my GitHub: https://github.com/baldwin-dev-co/mountaineer

like image 867
Ben Baldwin Avatar asked Mar 09 '26 22:03

Ben Baldwin


1 Answers

I just came across this problem as well, with a brand new React project.

Temporarily downgrading react-scripts from version 5.0.0 to 4.0.3 solved it for me, because after invoking npm install and npm run start this added the missing tsconfig.json file - which was the actual cause of the problem.

After this I could safely go back to 5.0.0 and everything worked fine.

like image 183
Johannes Charra Avatar answered Mar 12 '26 11:03

Johannes Charra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!