React Error – module not found: can’t resolve

Total
0
Shares

React throws the error, module not found: can’t resolve, when either the module is not defined or its path is incorrect.

Case 1: When module is not defined

If the module is not defined or it is spelled wrong then React won’t be able to recognize the component and will throw the module not found error. For example, you have created a file Header.js and while importing it in another component, you are using header.js.

Case 2: When module path is incorrect

You should know that by default React uses relative path. So, you can’t use absolute paths in imports. Suppose your directory structure is like this –

  • Folder1
    • SubFolder1
      • File1a
      • File1b
    • File1

You want to import File1b in File1a, then you can use two ways – Relative path or Absolute path.

Correct way – Relative path

import File1b from './File1b'

Wrong way – Absolute path

import File1b from './Folder1/SubFolder1/File1b'

Similarly, if you want to import File1 in File1a then –

Correct way –

import File1 from '../File1'

Wrong way –

import File1 from './Folder1/File1'

But if you are a fan of absolute paths, then there is a way. In your jsconfig.json or tsconfig.json files, add this –

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

now you can simply use the absolute paths for importing components.

These tips will help you in solving the issue of module not found React error.

    Tweet this to help others