Next.js is not recognizing '@types/react'

Viewed 9435

When I try to run my Next.js app with npm run dev I get an error message saying that I don't have the required packages to run Next with Typescript:

Please install @types/react by running:

        npm install --save-dev @types/react

If you are not trying to use TypeScript, please remove the tsconfig.json file from your package root (and any TypeScript files in your pages directory).

However, the module '@types/react' is installed. I tried running npm install --save-dev @types/react and got no error messages (just a bunch of warnings but I don't think they are the problem).

How can I solve this and run the project?

4 Answers

I used yarn add -D @types/react@18.0.1 and it worked perfectly! Netsu is right, seems like there is a bug in the current @types/react version (specifically v18.0.2).

My solution was to add --only to production:

RUN yarn install --only=production

An alternative approach i took here was to create a new nextjs project using npx create-next-app. And then copied the versions of all the dependencies and devDependencies.

Here is a sample package.json. I got this after create new nextjs project.

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "12.2.4",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "@types/node": "18.7.1",
    "@types/react": "18.0.17",
    "@types/react-dom": "18.0.6",
    "eslint": "8.21.0",
    "eslint-config-next": "12.2.4",
    "typescript": "4.7.4"
  }
}

Copy all the versions listed in the package.json you get after create new nextjs project. This will ensure that your core dependencies are compatible with each other.

Related