Cannot find module 'next' or its corresponding type declarations 无法找到模块 'next' 或其相应的类型声明
Cannot find module 'next' or its corresponding type declarations 无法找到模块 'next' 或其相应的类型声明
在Next.js项目中导入时出现Cannot find module '' or its corresponding type declarations.
的错误。
这个错误在每次导入时都会发生。 预览
Yarn版本:3.1.0-rc.2
Next版本: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" ], }
在使用TypeScript时,有时会遇到错误信息"Cannot find module 'next' or its corresponding type declarations"。这个问题的出现原因可能是由于TypeScript服务器的错误或缓存导致的。幸运的是,我们可以通过重新启动TypeScript服务器来解决这个问题。
以下是解决方法:
在Windows上使用VsCode时,可以按下"ctrl + shift + p"快捷键,然后选择"TypeScript: Restart TS server"来重新启动TypeScript服务器。
在Macbook上使用VsCode时,可以按下"⇧ + ⌘ + P or F1"快捷键,然后选择"TypeScript: Restart TS server"来重新启动TypeScript服务器。
重新启动TypeScript服务器通常可以解决这个问题。许多人发现这个解决方法非常有效,因为它可以帮助他们重新加载TypeScript模块并解决找不到模块的问题。
如果您遇到了"Cannot find module 'next' or its corresponding type declarations"的问题,不妨尝试这个简单的解决方法。重新启动TypeScript服务器可能会解决您的问题,从而让您的开发工作顺利进行。
问题出现的原因是在Yarn 2/3中,由于PnP的存在,对于node_modules文件夹中的模块的支持被移除了。解决方法如下:
1. 在项目根目录中创建一个`.yarnrc.yml`文件。
2. 在文件中插入`nodeLinker: node-modules`。
3. 在终端中运行`yarn`命令来重新创建node_modules文件夹。
通过执行上述3个步骤,问题将得到解决。
尽管它生成了node_modules文件夹,但Yarn PNP(Plug'n'Play)是非常棒的,它不使用node_modules文件夹,具有快速的依赖安装速度,同时使用较少的磁盘空间。但是,有必要确保所有项目依赖都支持PnP。尽管我在某个地方已经读到过next.js对PnP有标准支持,但我意识到它并不总是有效。`nodeLinker: node-modules`确保重新创建node_modules文件夹,并且yarn 2/3的行为类似于yarn 1或npm。
我通过同时使用Yarn PnP和Cuong Vu建议的解决方案使其工作。
在使用yarn 3和VSCode的情况下,如果遇到了(Cannot find module 'next' or its corresponding type declarations)这个问题,可以按照以下步骤设置编辑器:
1. 运行命令:yarn dlx /sdks vscode
2. 打开任意TypeScript文件
3. 按下ctrl+shift+p
4. 选择"Select TypeScript Version"
5. 选择"Use Workspace Version"
如果使用其他编辑器,请参考这里的说明。
有用户使用Neovim,而不是VS Code,但是在Yarn的编辑器SDK文档链接中找到了解决方法。
还有用户提到即使按照上述步骤进行设置,仍然出现了错误。有用户回复说需要先安装一个扩展,然后这个方法对他有效。提供的扩展链接是:marketplace.visualstudio.com/…
通过以上步骤可以解决(Cannot find module 'next' or its corresponding type declarations)的问题。