NextJS 14中Cannot use GraphQLSchema跨模块错误的排查与解决
NextJS结合type-graphql与apollo-server-lambda时GraphQLSchema跨模块错误解决
我在NextJS项目中尝试结合type-graphql与apollo-server-lambda(本地开发用NextJS API路由,生产环境部署到Lambda),运行时遇到以下错误:
Error: Cannot use GraphQLSchema [...] from another module or realm. Ensure that there is only one instance of "graphql" in the node_modules directory. If different versions of "graphql" are the dependencies of other relied on modules, use "resolutions" to ensure only one version is installed. https://yarnpkg.com/en/docs/selective-version-resolutions
解决步骤
- 先检查项目中安装的graphql版本情况,确认是否存在多版本实例:
# Yarn用户 yarn list graphql # NPM用户 npm ls graphql - 在
package.json中强制统一graphql版本:
若使用Yarn,添加resolutions字段:
若使用NPM,添加"resolutions": { "graphql": "^16.8.1" // 替换为你项目需要的稳定版本 }overrides字段:"overrides": { "graphql": "^16.8.1" // 替换为你项目需要的稳定版本 } - 清理依赖缓存并重新安装:
# Yarn用户 yarn cache clean && yarn install # NPM用户 npm cache clean --force && npm install - 重启NextJS开发服务器或重新部署Lambda服务,确保依赖生效。
原因说明
这个错误的核心是项目依赖树中存在多个不同版本的graphql包,导致type-graphql和apollo-server-lambda各自加载了不同的graphql实例,进而出现Schema跨模块无法兼容的问题。通过强制统一graphql版本,能确保所有依赖都使用同一个实例,解决该错误。
内容的提问来源于stack exchange,提问作者Tobi
相关产品推荐
相关产品推荐

