React is one of the most popular web development frameworks around. React is so popular because of the thousands of extensions and packages developers can download and integrate into their projects for added functionality.
However, adding external packages to a project also adds uncalled for errors and bugs, especially when React can’t detect a package you’re trying to load into the project.
In this article, we’re talking about the “module not found: Error: can’t resolve” problem, which happens when React can’t load a package you’re referring to in your code.
Install the package
The first thing you should do is check if the package you’re using has been installed and added as a dependency. Depending on whether you’re using NPM or Yarn, you can install the required package using the following command.
npm install [package name]
Also, make sure that you’re importing the package before referring to it in your code. The same goes for any components that you’re using as well.
Delete the node_modules folder
If installing the package right away isn’t helping, you can delete the entire node_modules folder and the package-lock,json file to refresh all dependencies in your project. This is effectively equivalent to reinstalling the project. Open a terminal, navigate to the project root directory and enter the following commands.
rm -rf node_modules npm install
Try restarting the project now, and your modules should load just fine.
Check your files
If you’re facing this error when importing local files or components, check to see if everything is in order. Your files end with the .js extension, and you’re importing them properly, keeping in mind the folder structure and the case you used when naming files. Use periods and slashes according to your folder directory structure when importing a file.
Alternatively, you can mention the entire path just to be sure.
import Component from /components/subfolder/anyotherfolder
Also, make sure that your folder names don’t contain spaces, colons, or special characters like hashes or asterisks.