Heroku部署时出现Cannot find module 'webpack'问题求助
Hey there, let’s work through this "Cannot find module 'webpack'" error you’re hitting on Heroku. Since your app runs perfectly locally, this is almost definitely a quirk with how Heroku handles dependency installation or build caching. Here are the most common fixes to try:
1. Make sure webpack is in the right dependency group
Heroku skips installing devDependencies by default when running in production mode. If webpack is only listed under devDependencies in your package.json, that’s why it’s missing on Heroku!
You have two solid options here:
- Move webpack from
devDependenciestodependenciesinpackage.json(if it’s needed for production runtime) - Or set a Heroku config to install dev dependencies specifically for your build step (better practice if webpack is only used for building):
Alternatively, add aheroku config:set NPM_CONFIG_PRODUCTION=falseheroku-postbuildscript to handle this cleanly without disabling production mode entirely:"scripts": { "heroku-postbuild": "npm install --only=dev && npm run build", "build": "webpack --config webpack.dev.babel.js" }
2. Purge Heroku’s build cache
Sometimes Heroku hangs onto old dependency caches and skips reinstalling updated packages. Clear the cache to force a fresh, clean install:
heroku builds:cache:purge
Then push your code again—this will make Heroku pull and install all dependencies from scratch.
3. Sync your package.json and lockfile
If you added webpack to your dependencies but didn’t commit the updated package-lock.json (or yarn.lock if you use Yarn), Heroku might be installing a mismatched or missing version.
Run these steps locally first to get everything in sync:
npm install git add package.json package-lock.json git commit -m "Sync dependencies and lockfile" git push heroku main
4. Verify your build script order
Make sure Heroku runs your webpack build after dependencies are installed. Heroku automatically looks for a build script in package.json and runs it during deployment—double-check that your build script points to the correct webpack config (in your case, webpack.dev.babel.js).
5. Confirm your webpack config path is correct
Double-check that webpack.dev.babel.js is in your project root, or that the path referenced in frontendMiddleware.js is accurate. Local directory paths can sometimes behave differently than on Heroku if there’s a subtle folder structure mismatch.
After trying these steps, redeploy your app and see if the error clears up. If you still run into issues, feel free to share more details about your package.json scripts or project structure, and I’ll help you dig deeper!
内容的提问来源于stack exchange,提问作者Baker 3

