Cannot find module 'next' or its corresponding type declarations

Viewed 6005

Getting Cannot find module '' or its corresponding type declarations. when importing in Next.js project.

This happens on every single import. Preview

Yarn version : 3.1.0-rc.2
Next version: 11.1.2

tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "importHelpers": true,
    "jsx": "preserve",
    // "baseUrl": "src"
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ],
}
5 Answers

Maybe just restarting the TS server can work.

type: ctrl + shift + p

choose: > TypeScript: Restart TS server

If you're using yarn 3, then you need to follow those steps to set up your VSCode:

  • Run yarn dlx @yarnpkg/sdks vscode
  • Open any TypeScript file
  • Press ctrl+shift+p
  • Choose "Select TypeScript Version"
  • Pick "Use Workspace Version"

Read here for other editors

Before attempting other solutions:

  1. Double check you have a node_modules folder
  2. If not, run yarn (or npm i) to (re)install the modules

Accidentally deleting the node_modules folder is the simplest explanation for the TS2307 Cannot find module '' error.

It's also supported by OP comments

"i don't have node_module folder. Only .yarn and yarn.lock"

h/t @geisterfurz007's comments.

I added this to my tsconfig.json file I can see you have it already, but it was not part of my solution

"moduleResolution": "node",

I tried solution suggested by Cuong Vu and many others and it didn't work. For me what worked was the following solution:

In Yarn 2/3, support for modules in the node_modules folder is removed because of PnP. Follow the steps below to resolve the issue.

  1. Create a .yarnrc.yml file in the project root,
  2. Insert in the file nodeLinker: node-modules.
  3. Run the command yarn in the terminal to recreate the node_modules folder.

Following all 3 steps the problem will be solved.

Related