221

I can't believe that I'm asking an obvious question, but I still get the error in console log.

Console says that it can't find the module in the directory, but I've checked at least 10 times for typos. Anyways, here's the component code.

I want to render Header in root

import React, { Component } from 'react'
import Header from './src/components/header/header'
import logo from './logo.svg'
import './App.css'

class App extends Component {
  render() {
    return (
      <Header/>
    );
  }
}

export default App;

This is the Header component

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import navBar from './src/components/header/navBar'
import './src/css/header.css'

class Header extends Component {
    render() {
        return {
            <div>
             <div id="particles-js"></div>
             <navBar/>
             <Title/>
          </div>
        };
    }
}

ReactDOM.render(<Header/>, document.getElementById('header'));

I've checked at least 10 times that the module is at this location ./src/components/header/header, and it is (folder "header" contains "header.js").

Yet, React still throws this error:

Failed to compile

./src/App.js Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'

npm test says the same thing.

6
  • 3
    add export default Header; on your 'header file' Commented Jun 8, 2017 at 15:00
  • 2
    Still doesn't work. Commented Jun 8, 2017 at 15:01
  • 4
    It seems you need import Header from './components/header/header' w/o src. File path is relative to importing file path. Then you need to export Header from header.js and fix App.render method. Commented Jun 8, 2017 at 15:04
  • If I take the components folder outside from src folder, then it tells me that I need to modify the node_modules files, which is not my attention. Commented Jun 8, 2017 at 15:06
  • 12
    You don't need to move anything. You have incorrect relative path. If you are importing inside './src/app.js' it should be import smth from './components/header/header' Same for this line import navBar from './src/components/header/navBar' it should be relative to current path import navBar from './navBar' Commented Jun 8, 2017 at 15:10

28 Answers 28

208

The way we usually use import is based on relative path.

. and .. are similar to how we use to navigate in terminal like cd .. to go out of directory and mv ~/file . to move a file to current directory.

my-app/
  node_modules/
  package.json
  src/
    containers/card.js
    components/header.js
    App.js
    index.js

In your case, App.js is in src/ directory while header.js is in src/components. To import you would do import Header from './components/header'. This roughly translate to in my current directory, find the components folder that contain a header file.

Now, if from header.js, you need to import something from card, you would do this. import Card from '../containers/card'. This translate to, move out of my current directory, look for a folder name containers that have a card file.

As for import React, { Component } from 'react', this does not start with a ./ or ../ or / therefore node will start looking for the module in the node_modules in a specific order till react is found. For a more detail understanding, it can be read here.

Sign up to request clarification or add additional context in comments.

Comments

42

If you create an application with react-create-app, don't forget set environment variable:

NODE_PATH=./src

Or add to .env file to your root folder;

2 Comments

This is the one the solved for me. I added a simple App.css to src/ and did import App.css. But that gave me the error of the question. This answer solved the issue.
I thought I was crazy my react app wasn't working as expected and I just paste this environment variable and it just works... The thing is why it doesn't come with this file already... I don't get it, if react spends twelve minutes downloading a bunch of dependencies why it doesn't come with these file.
36

Deleted the package-lock.json file & then ran

npm install

Read further

2 Comments

Thank you so much, I had the following error: Module not found: Can't resolve... TextInput and your solution solved it
This is good idea to do on any project we get from outside.
31

in my case, The error message was

Module not found: Error: Can't resolve '/components/body

While everything was in the correct directory.

I found that renaming body.jsx to body.js resolve the issue!

So I added this code in webpack.config.js to resolve jsx as js

 module.exports = {
  //...
  resolve: {
    extensions: ['.js', '.jsx']
  }
};

And then build error gone!

1 Comment

Indeed, in my case I had forgotten to put ".tsx" in the extensions array.
16

Adding NODE_PATH as environment variable in .env is deprecated and is replaced by adding "baseUrl": "./src", to compilerOptions in jsconfig.json or tsconfig.json.

Reference

Comments

15

I solved by putting the file extension

import MyComponent from "src/components/MyComponent";

to

import MyComponent from "src/components/MyComponent.tsx";

2 Comments

? TS2691: An import path cannot end with a '.tsx' extension.
9

I think its the double use of header. I just tried something similar myself and also caused issues. I capitalized my component file to match the others and it worked.

import Header from './src/components/header/header';

Should be

import Header from './src/components/header/Header';

2 Comments

I hate this gave me the answer because I havd the same folder structure and instead of doing ./components/header/header I was doing ./components/header ... I am too old for those kinda mistakes lolol
@Chris what's up with that? I also fixed mine doing the same. So confusing. Anyone with a simple explanation?
9

There is a better way you can handle the import of modules in your React App. Consider doing this:

Add a jsconfig.json file to your base folder. That is the same folder containing your package.json. Next define your base URL imports in it:

//jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}

Now rather than calling ../../ you can easily do this instead:

import navBar from 'components/header/navBar'
import 'css/header.css'

Notice that 'components/' is different from '../components/'

It's neater this way.

But if you want to import files in the same directory you can do this also:

import logo from './logo.svg'

Comments

3

I had a similar issue.

Cause:

import HomeComponent from "components/HomeComponent";

Solution:

import HomeComponent from "./components/HomeComponent";

NOTE: ./ was before components. You can read @Zac Kwan's post above on how to use import

Comments

3

You can try to execute 'npm install' in the app folder. This might also solve the problem. It worked for me.

1 Comment

specifically if the package was installed with another user previously. ie: check access privileges of files/folders
3

I faced the same issue when I created a new react app, I tried all options in https://github.com/facebook/create-react-app/issues/2534 but it didn't help. I had to change the port for the new app and then it worked. By default, apps use the port 3000.I changed the port to 8001 in package.json as follows:

  "scripts": {
    "start": "PORT=8001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Comments

3

If you are using create-react-app, and have just added typescript to it, check whether a tsconfig.json has been auto-generated for you. The CRA docs say that it should be, but there seems to be a bug at the moment where it is not being generated.

If the tsconfig.json is missing, there's a few ways to create one yourself.

  • Copy one off the internet or from another repo
  • npx tsc --init
  • Create a fresh project somewhere else using npx create-react-app my-ts-proj --template typescript and then copy the tsconfig over from there

Comments

1

I just had this issue from auto-importing a component, no type or webpack config issues.

What fixed it was changing the import from relative to the app root directory to relative to the file:

import MyComponent from "src/components/MyComponent";

to

import MyComponent from "../components/MyComponent";

If you're getting this from Visual Studio Code auto-importing via the shortest route, you can change it so it imports relatively. By going here:

menu File → Preferences → Settings → User Settings,

"typescript.preferences.importModuleSpecifier": "relative"

Comments

0

you should change import Header from './src/components/header/header' to

import Header from '../src/components/header/header'

Comments

0

replace ReactDOM.render(<Header/>, document.getElementById('header')); by export default Header in Header.js

Comments

0

It is working for me just (./) no need src here

import Header from './components/header/header'

Comments

0

You might be importing .tsx file inside a .js file. Ensure that if you are working on a javascript source, you have extensions .js or .jsx not .tsx :)

Comments

0

Also, with framework I got the same error after deleting the "loading.tsx" (not imported anywhere). Just in case you have similar situation. I resolved by removing the .next/cache/webpack. Or remove the entire .next/cache directory

Comments

0

I am sure you have solved this by now but let me add it for future reference. I did encounter the same issue and my issue was on renaming and path refernce. Have a look at this, code when getting the error

import Account from "./account";

The problem is with path reference and naming

Here is the correct code

import Account from "./pages/dashboard/Account";

Comments

0

I face the same odd issue ,everything will be fine when local npm run dev
but when depoly and run build, sth happend:
when import Hearder from "./common/Header";
it would Module not found: Can't resolve ./commom/Header
I checked the tsconfig and changed my baseUrl, it not working,
but after import Hearder from "./common/myHeader"; it works...
maybe double "Header" is NOT allowed .

btw my header file is

 const Hearder = () => {
  const { viewPort } = useViewport();
  return <div className="header">{viewPort}</div>;
};

export default Hearder;

Comments

0

i found the same problem and now i use :

  • "react": "^18.3.1",
  • "react-router-dom": "^6.23.0",

the solution is to change

from

import Header from './src/components/header/header'

import Header from './src/components/header/header'

to

import Header from './src/components/header/header.js' or

import Header from './src/components/header/header.jsx'

Comments

0

For any Ruby on Rails devs who run into this issue (Error: Cannot find module ‘path’)…

When importing modules, components, handlers, etc. in react, the import reference is relative to the location of the file you’re importing vs a rails resource or asset which is absolute to the rails structure.

In rails, if you’re accessing an image in the app/assets/images directory, it’s an absolute reference to the assets folder and looks something like this:

<%= image_tag “image.png” %>

Any sub-folders are referenced by adding that folder to the filename

<%= image_tag “home/image.png” %>

(More info on the rails asset pipeline here)

In react if you have a structure like this:

—app
——javascript 
————components 
——————Sidebar.jsx 
————utils
——————sidebarUtil.js

And you want to import a handler from your app/javascript/utils/sidebarUtil.js into app/javascript/components/Sidebar.jsx, your import will look like this:

import { handler } from “../../utils/sidebarUtil“

Where each .. takes you up one level in your file structure just like in your terminal when changing directory.

If the handler you want to import is in a file in the same directory, use

import { handler } from “./moduleName”

Comments

-1

You need to be in project folder, if you are in src or public you have to come out of those folders. Suppose your react-project name is 'hello-react' then cd hello-react

Comments

-1

I was facing the same problem and I resolved it. See if your index.js file is in src folder, then what ever file you are importing, the folder containing that must also be inside the src folder.

That means if your components folder is outside the src folder, just drag it inside the src folder in your editor because the files outside of src folder are not imported.

Then you shall be able to import using ./components/header/header(in this case) enter image description here

Comments

-1

For me, I had the input correct but npm start can be buggy (at least using it with Hyper terminal on Windows and Linux). If I move files to different folders, npm start doesn't pick up on these changes. I need to cancel npm start process, make the move, save and then run npm start and it will see the files now.

Comments

-3

In my case I rename a component file, an VS Code add the below line of code for me:

import React, { Component } from "./node_modules/react";

So I fixed by removing the: ./node_modules/

import React, { Component } from "react";

Cheers!

Comments

-3

I think it may help you-

Read your error carefully-./src/App.js Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'

just write- ./header/header instead ./src/components/header/header in App.js

if it doesnt work try to change header file name may be head

Comments

-4

Check for the import statements.It should be ended with semicolon. If you miss any, you will get this error.

Also check whether following import statement added in you component.

import { threadId } from 'worker_threads';

If so remove that line. It works for me.

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.