To solve the "Cannot find module react or its corresponding type declarations" error, install the module and its type definitions by running the commands npm install react and npm i --save-dev @types/react . Copied! Now you should be able to import the react library with the following line of code. Copied!
To solve the error "Module not found: Error: Can't resolve 'axios'", make sure to install the axios package by opening your terminal in your project's root directory and running the command npm install axios and restart your development server.
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.
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;
Deleted the package-lock.json file & then ran
npm install
Read further
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
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!
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';
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With