Can't resolve module (not found) in React.js

Solution 1:

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.

Solution 2:

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;

Solution 3:

Deleted the package-lock.json file & then ran

npm install

Read further

Solution 4:

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

Solution 5:

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!