Next.js部署Heroku时因Webpack错误构建失败求助
Next.js部署Heroku构建失败排查
问题描述
使用Heroku CLI部署Next.js应用,执行git push heroku master时构建失败,本地可正常构建,但Heroku上构建报错。
Package.json
{ "name": "XXXX-ecommerce", "version": "0.1.0", "engines": { "node": "18.x", "npm": "7.x" }, "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "heroku-postbuild": "npm run build", "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "@apollo/client": "^3.7.0", "@nacelle/react-yotpo": "^8.0.0", "axios": "^1.1.3", "cookie": "^0.5.0", "cookie-cutter": "^0.2.0", "graphql": "^16.6.0", "lodash": "^4.17.21", "lodash.filter": "^4.6.0", "lodash.uniqby": "^4.7.0", "next": "12.3.1", "react": "18.2.0", "react-collapsible": "^2.10.0", "react-dom": "18.2.0", "react-rating": "^2.0.5", "swiper": "^8.4.2" }, "devDependencies": { "eslint": "8.24.0", "eslint-config-next": "12.3.1" } }
Heroku构建日志
info - Creating an optimized production build... Failed to compile. ./components/card.js Module not found: Can't resolve 'lodash.uniqBy' in '/tmp/build_54073365/components' Import trace for requested module: ./components/card.js ./components/productSlider.js ./pages/products/[id].js Module not found: Can't resolve 'lodash.uniqBy' in '/tmp/build_54073365/pages/products' > Build failed because of webpack errors -----> Build failed We're sorry this build is failing! You can troubleshoot common issues here: https://devcenter.heroku.com/articles/troubleshooting-node-deploys If you're stuck, please submit a ticket so we can help: https://help.heroku.com/ Love, Heroku ! Push rejected, failed to compile Node.js app. ! Push failed
问题原因与解决方案
原因
Heroku使用的Linux环境是大小写敏感的,而你本地系统(比如Windows/macOS)默认大小写不敏感。你在package.json中安装的是lodash.uniqby(by为小写),但代码里导入的是lodash.uniqBy(By的B大写),导致Linux环境下找不到对应模块。
解决方法
两种方案二选一:
- 修正导入语句的大小写:把代码中所有
import ... from 'lodash.uniqBy'改成import ... from 'lodash.uniqby'(确保by是小写) - 从lodash主包导入:直接使用
import uniqBy from 'lodash/uniqBy',这种方式不仅能避免大小写问题,还能减少打包体积,更推荐。
修改后重新提交代码,执行git push heroku master即可完成部署。
内容的提问来源于stack exchange,提问作者user254153
相关产品推荐
相关产品推荐

