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

Webpack生成的bundle.js无法执行,求问题排查与解决方法

Webpack打包后bundle.js无法运行排查

问题描述

使用Webpack运行Web应用时,bundle.js突然停止工作,即使是简单的console.log语句也无法执行,需排查原因。

Webpack配置文件(webpack.config.js)

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.(js|html)$/, // 匹配.js和.html文件
        enforce: "pre",
        use: ['source-map-loader', 'html-loader'],
      },
    ],
  },
  ignoreWarnings: [/Failed to parse source map/],
  watch: true,
};

项目目录结构

-public
  -dist
    -bundle.js
  -src
    -index.js
index.html

index.html代码

<html>
  <head></head>
  <body>
    <script src="./dist/bundle.js"></script>
  </body>
</html>

index.js代码

console.log('You won't see this');

错误分析与解决方案

1. index.js存在语法错误

console.log语句中,字符串用单引号包裹,但内部的won't包含未转义的单引号,导致JS语法解析失败,Webpack打包时会生成无效bundle或直接终止打包。

修复方法:

  • 转义内部单引号:
    console.log('You won\'t see this');
    
  • 或改用双引号包裹字符串:
    console.log("You won't see this");
    

2. Webpack输出路径与实际目录不匹配

配置中output.path设置为根目录下的dist,但项目里dist属于public文件夹,导致打包生成的bundle.js位置和index.html引用路径不对应,浏览器无法加载正确文件。

修复方法:
修改output.path指向public下的dist目录:

output: {
  filename: 'bundle.js',
  path: path.resolve(__dirname, 'public/dist')
},

3. 模块规则配置不合理

将JS和HTML文件放在同一个pre规则中处理,source-map-loader仅适用于JS文件的source map解析,对HTML文件处理会触发无效警告,可能干扰打包流程。

修复方法:
拆分JS和HTML的处理规则:

module: {
  rules: [
    // 处理JS文件的source map
    {
      test: /\.js$/,
      enforce: "pre",
      use: ['source-map-loader'],
    },
    // 处理HTML文件
    {
      test: /\.html$/,
      use: ['html-loader'],
    },
  ],
},

4. index.html引用路径错误

调整引用路径,确保浏览器能找到public/dist下的bundle.js:

<script src="./public/dist/bundle.js"></script>

完成以上修复后,重启Webpack watch模式,即可生成可正常运行的bundle.js,console.log语句也能正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:29:55