在Next.js 15中添加Shadcn组件时遭遇模块缺失错误
在Next.js项目中添加shadcn/ui Toast组件时遇到模块缺失错误
我在Next.js项目中尝试添加shadcn/ui的Toast组件时触发了以下错误,该项目在其他设备上运行正常,但当前设备始终出现这个问题。我已经尝试更新Node.js和npm到最新版本(node: v22.12.0、npm: 11.0.0),但问题依然存在。
错误信息
npx shadcn@latest add toast node:internal/modules/esm/resolve:204 const resolvedOption = FSLegacyMainResolve(pkgPath, packageConfig.main, baseStringified); ^ Error: Cannot find package 'C:\Users\user\AppData\Local\npm-cache\_npx\d66c5096c7023bfb\node_modules\is-regexp\index.js' imported from C:\Users\user\AppData\Local\npm-cache\_npx\d66c5096c7023bfb\node_modules\stringify-object\index.js at legacyMainResolve (node:internal/modules/esm/resolve:204:26) at packageResolve (node:internal/modules/esm/resolve:846:14) at moduleResolve (node:internal/modules/esm/resolve:926:18) at defaultResolve (node:internal/modules/esm/resolve:1056:11) at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:654:12) at #cachedDefaultResolve (node:internal/modules/esm/loader:603:25) at ModuleLoader.resolve (node:internal/modules/esm/loader:586:38) at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:242:38) at ModuleJob._link (node:internal/modules/esm/module_job:135:49) { code: 'ERR_MODULE_NOT_FOUND' } Node.js v22.12.0
项目package.json内容
{ "name": "new", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev ", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@hookform/resolvers": "^3.10.0", "@radix-ui/react-accordion": "^1.2.2", "@radix-ui/react-alert-dialog": "^1.1.4", "@radix-ui/react-label": "^2.1.1", "@radix-ui/react-navigation-menu": "^1.2.3", "@radix-ui/react-slot": "^1.1.1", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "framer-motion": "^12.0.0", "lucide-react": "^0.473.0", "next": "15.1.3", "react": "^19", "react-dom": "^19", "react-hook-form": "^7.54.2", "tailwind-merge": "^2.6.0", "tailwindcss-animate": "^1.0.7", "zod": "^3.24.1" }, "devDependencies": { "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", "@types/yandex-maps": "^2.1.36", "eslint": "^9", "eslint-config-next": "15.1.5", "postcss": "^8.5.1", "tailwindcss": "^3.4.17", "typescript": "^5" } }
解决方法
清理npm缓存并重试:错误源于npx临时缓存中的依赖缺失,执行以下命令清理缓存后重新安装:
npm cache clean --force npx shadcn@latest add toast更换包管理器尝试:如果清理缓存无效,改用pnpm或yarn执行安装命令:
# pnpm pnpm dlx shadcn@latest add toast # yarn yarn dlx shadcn@latest add toast手动安装缺失依赖:临时安装缺失的
is-regexp包后再运行shadcn命令:npm install is-regexp npx shadcn@latest add toast降级Node.js版本:Next.js 15与React 19可能和Node.js 22存在兼容性问题,可尝试降级到Node.js 20.x LTS版本,重新安装项目依赖后再执行shadcn命令。
内容的提问来源于stack exchange,提问作者Anvar Adizov
相关产品推荐
相关产品推荐

