NextJS执行next build命令在Linux服务器上无限挂起求助
问题描述
- 本地Windows 10环境执行
next build可正常构建Next.js应用,但在运行内核版本为linux 4.18.0-372.9.1.1.lve.el8.x86_64的Linux服务器上,该命令会无限挂起 - 现有项目及服务器上新建的空白Next.js项目均出现此问题
- 已尝试在
next.config.js中配置跳过linting和类型检查,问题未解决 - 构建期间CPU使用率飙升至92%-100%,服务器闲置时CPU使用率仅14%
- 疑问:是否可能缺少系统依赖?如何在执行
next build时跳过Jest测试?
当前next.config.js配置如下:
// next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, distDir: "./build", images: { remotePatterns: [ { protocol: "http", hostname: "localhost", port: "1337", pathname: "/uploads/**", }, { protocol: "http", hostname: "127.0.0.1", port: "1337", pathname: "/uploads/**", }, ], }, async redirects() { return [ { source: "/news", destination: "/", permanent: false, }, ]; }, }; const withBundleAnalyzer = require("@next/bundle-analyzer")({ enabled: process.env.ANALYZE === "true", }); module.exports = withBundleAnalyzer(nextConfig);
解决建议
一、排查系统依赖缺失问题
- 对齐Node.js版本:确保服务器上的Node.js版本与本地Windows环境完全一致(推荐用nvm管理版本),Next.js对Node.js版本有明确兼容要求,版本不匹配可能引发构建异常
- 安装基础构建工具:部分Linux发行版缺少编译依赖,可执行以下命令补充:
# 适用于CentOS/RHEL 8系统 sudo dnf install gcc-c++ make python3 - 清理缓存后重试:清除项目缓存和Node.js全局缓存,重新安装依赖并构建:
rm -rf node_modules .next build npm cache clean --force npm install npm run build
二、构建时跳过Jest测试的方法
Next.js默认不会在next build阶段自动执行Jest测试,若你的项目通过自定义脚本绑定了构建与测试,可通过以下方式跳过:
- 修改package.json脚本:直接剥离构建命令中的测试环节:
{ "scripts": { "build": "next build" } } - 用环境变量控制测试执行:在构建时传入跳过测试的环境变量,同时在测试逻辑中判断该变量:
- 构建命令:
SKIP_TESTS=true npm run build - 在
jest.config.js或自定义测试脚本中加入判断:if (process.env.SKIP_TESTS === 'true') { process.exit(0); }
- 构建命令:
内容的提问来源于stack exchange,提问作者Ibrahim A. Elaradi
相关产品推荐
相关产品推荐

