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

部署Webpack项目到Heroku时出现404错误:bundle.js未找到

排查Heroku部署Webpack项目bundle.js 404问题的步骤

作为Webpack新手遇到这种部署路径问题很常见,我帮你梳理几个核心排查方向和解决办法,一步步来定位问题:

1. 先确认Heroku是否执行了Webpack构建

bundle.js找不到的最直接原因可能是服务器上根本没生成这个文件,你需要检查:

  • 打开你的package.json,确认是否包含Webpack构建脚本:
    "scripts": {
      "build": "webpack --mode production",
      "start": "npm run build && node server.js" // 启动前先执行构建
    }
    
    或者可以添加postinstall脚本,让Heroku在安装依赖后自动构建:
    "scripts": {
      "build": "webpack --mode production",
      "postinstall": "npm run build",
      "start": "node server.js"
    }
    
  • 登录Heroku查看日志(用命令heroku logs --tail),搜索是否有Webpack构建的输出内容。如果看不到打包相关日志,说明Heroku没执行构建步骤,那自然没有bundle.js。
  • 注意:如果Webpack、html-webpack-plugin这类构建工具只放在devDependencies里,Heroku默认在生产环境会跳过安装dev依赖,导致无法构建。你可以把这些依赖移到dependencies里,或者执行heroku config:set NPM_CONFIG_PRODUCTION=false让Heroku安装dev依赖。

2. 检查Webpack配置的输出路径

Webpack的output配置直接决定bundle.js生成的位置和引用路径,确保配置正确:

const path = require('path');

module.exports = {
  // ...其他配置
  output: {
    path: path.resolve(__dirname, 'dist'), // 必须是绝对路径,指定bundle.js生成的目录
    filename: 'bundle.js',
    publicPath: '/' // 关键!确保静态资源的根引用路径正确
  }
};

另外,别把输出目录(比如dist)加到.gitignore里——如果是本地构建后推代码,忽略的话Heroku拉不到文件;如果是在Heroku上构建,忽略目录没问题,但要确保构建能正常生成它。

3. 验证server.js的静态文件服务配置

如果用Express做服务器,必须正确指定静态文件的目录,让服务器能找到bundle.js:

const express = require('express');
const path = require('path');
const app = express();

// 这里要和Webpack output.path完全对应,比如是dist就写dist
app.use(express.static(path.resolve(__dirname, 'dist')));

// 单页应用需要添加这个路由,避免刷新页面时404
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

如果静态目录指向错误,服务器就无法响应/bundle.js的请求。

4. 检查index.html里的bundle.js引用路径

手动写的index.html很容易出现路径错误,推荐用html-webpack-plugin自动生成带正确引用的index.html:

  • 先安装插件:npm install html-webpack-plugin --save-dev
  • 在webpack.config.js里配置:
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      // ...其他配置
      plugins: [
        new HtmlWebpackPlugin({
          template: './src/index.html' // 你的源html文件路径
        })
      ]
    };
    
    这样Webpack会自动把生成的index.html放到dist目录,并且插入正确的bundle.js引用,不用手动写<script>标签,彻底避免路径错误。

如果非要手动写,确保用绝对路径:<script src="/bundle.js"></script>,不要用相对路径(比如src="bundle.js"),否则路由跳转时会出现路径混乱。

5. 用Heroku日志定位具体错误

执行heroku logs --tail查看实时日志,重点看:

  • 是否有Webpack构建失败的报错(比如依赖缺失、语法错误)
  • 当请求/bundle.js时,服务器返回的404日志里有没有显示实际查找的路径,对比你的配置看是否匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:08:59