如何修复在Next.js中导入@lens-protocol/wagmi时的ERR_UNSUPPORTED_DIR_IMPORT错误?
Next.js 导入 @lens-protocol/wagmi 时的 ERR_UNSUPPORTED_DIR_IMPORT 错误修复方案
错误详情
Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/Users/......./node_modules/@apollo/client/link/context' is not supported resolving ES modules imported from /Users/....../node_modules/@lens-protocol/api-bindings/dist/index.js Did you mean to import @apollo/client/link/context/context.cjs? at new NodeError (node:internal/errors:371:5) at finalizeResolution (node:internal/modules/esm/resolve:412:17) at moduleResolve (node:internal/modules/esm/resolve:932:10) at defaultResolve (node:internal/modules/esm/resolve:1044:11) at ESMLoader.resolve (node:internal/modules/esm/loader:422:30) at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40) at ModuleWrap. (node:internal/modules/esm/module_job:76:40) at link (node:internal/modules/esm/module_job:75:36) { code: 'ERR_UNSUPPORTED_DIR_IMPORT', url: 'file:///Users/sebastianserrano/projects/rpsocial/node_modules/@apollo/client/link/context', page: '/' }
修复方案
1. 配置 Next.js 的 transpilePackages
修改 next.config.js,添加需要转译的依赖包,让 Next.js 处理模块解析冲突:
/** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['@lens-protocol/api-bindings', '@apollo/client'], } module.exports = nextConfig
转译后 Next.js 会统一处理这些第三方包的模块格式,避免 ES 模块和 CommonJS 之间的解析问题。
2. 调整 Apollo Client 版本
当前 @apollo/client 版本可能存在模块导出缺陷,试试锁定到稳定兼容版本:
npm install @apollo/client@3.7.17 # 用 yarn 的话执行下面这句 yarn add @apollo/client@3.7.17
3. 添加 Webpack 别名(临时 workaround)
在 next.config.js 里加别名,直接指向正确的文件路径,绕过目录导入的问题:
const path = require('path') /** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.resolve.alias['@apollo/client/link/context'] = path.resolve( __dirname, 'node_modules/@apollo/client/link/context/context.cjs' ) return config }, } module.exports = nextConfig
注意这是临时解决办法,后续依赖更新后可能需要调整或移除。
内容的提问来源于stack exchange,提问作者sebastian serrano
相关产品推荐
相关产品推荐

