You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS最新版部署报错:Named export 'useContext' not found

Next.js 云端部署 React 模块导入错误解决方案

问题背景

使用以下package.json配置:

{
  "dependencies": {
    "@nextui-org/react": "^2.2.8",
    "axios": "^1.6.0",
    "framer-motion": "^10.16.4",
    "next": "latest",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.4.16",
    "eslint": "^8",
    "eslint-config-next": "14.0.0",
    "postcss": "^8.4.31",
    "tailwindcss": "^3.3.5",
    "typescript": "^5"
  }
}

采用Next.js官方多环境Docker示例中的生产Dockerfile部署后,出现内部服务器错误,日志报错:

import $73SJx$react, {useContext as $73SJx$useContext, useState as $73SJx$useState, useMemo as $73SJx$useMemo, useLayoutEffect as $73SJx$useLayoutEffect, useRef as $73SJx$useRef} from "react";
SyntaxError: Named export 'useContext' not found. The requested module 'react' is a CommonJS module, which may not support all module.exports as named exports.

核心原因

该错误源于ESM(ECMAScript模块)与CommonJS模块的兼容性冲突,大概率是依赖版本不匹配、Docker构建缓存导致依赖安装异常,或是Next.js模块解析策略与第三方库(如NextUI)的模块格式不兼容。

解决方案

1. 锁定Next.js版本,消除版本不一致

package.json中next使用latest可能拉取到与eslint-config-next@14.0.0不兼容的版本,将其改为固定版本:

"next": "14.0.0"

2. 清理依赖并重新安装

删除本地依赖缓存与锁文件,确保依赖版本一致:

rm -rf node_modules package-lock.json
npm install

3. 调整Next.js模块解析配置

在项目根目录创建/修改next.config.js,添加以下配置以兼容第三方库的模块格式:

/** @type {import('next').NextConfig} */
const nextConfig = {
  // 转译NextUI等第三方库,确保模块格式兼容
  transpilePackages: ['@nextui-org/react'],
  // 宽松处理ESM外部依赖,缓解CommonJS/ESM冲突
  experimental: {
    esmExternals: 'loose',
  },
}

module.exports = nextConfig

4. 修复Docker构建逻辑

确保Docker构建过程中正确安装依赖并避免缓存干扰:

  • 在Dockerfile中,添加清理缓存的步骤(如在npm install前删除node_modules)
  • 构建镜像时禁用缓存:docker build --no-cache -t your-app .
  • 确认Dockerfile中NODE_ENV设置为production,且构建阶段正确复制了生产依赖

5. 验证依赖版本一致性

检查实际安装的React版本,确保没有被第三方依赖降级:

npm ls react

输出应显示react@18.2.0,无其他版本的React被安装。

验证步骤

  1. 完成上述配置修改后,本地运行npm run build确认构建无错误
  2. 重新构建Docker镜像并部署到云端
  3. 访问应用,确认内部服务器错误已解决

内容的提问来源于stack exchange,提问作者EdDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 08:43:35