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

Webpack新手求助:执行打包命令后提示无法解析hello.bundle.js

解决Webpack 4执行命令时"Module not found: Can't resolve 'hello.bundle.js'"的问题

刚接触Webpack遇到这种问题很正常,我帮你拆解下问题原因和解决办法:

问题根源

你执行的命令webpack hello.js hello.bundle.js,在Webpack 4的规则里会被解析成把hello.js和hello.bundle.js同时作为入口文件来打包,但hello.bundle.js是你期望生成的输出文件,根本还不存在,所以Webpack会报错找不到这个模块。Webpack 4已经取消了旧版本里webpack <入口> <出口>的简写语法,必须明确指定输出参数。

解决方案

这里有几种实用的解决方式,你可以根据自己的需求选:

1. 直接修正命令行参数(快速解决)

用-o(或完整的--output)参数明确指定输出文件,同时Webpack 4要求必须指定运行模式(development或production),否则会弹出警告。正确的命令应该是:

webpack hello.js -o hello.bundle.js --mode development

或者更完整的写法:

webpack --entry hello.js --output hello.bundle.js --mode production

执行这个命令后,Webpack就会把hello.js作为入口,打包生成你想要的hello.bundle.js文件。

2. 使用Webpack配置文件(推荐,适合后续扩展)

如果之后你的项目功能变复杂,推荐创建webpack.config.js配置文件,把所有打包规则集中管理:

module.exports = {
  mode: 'development', // 开发模式下代码不压缩,换成'production'会生成压缩后的生产环境代码
  entry: './hello.js', // 指定入口文件路径
  output: {
    filename: 'hello.bundle.js' // 指定输出文件名
  }
};

配置好之后,直接在终端执行:

webpack

Webpack会自动读取这个配置文件完成打包。

3. 在package.json里添加打包脚本(更便捷)

你可以修改package.json的scripts字段,把打包命令写进去,之后只需执行npm run build就能打包:

{
  "name": "webpackdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack hello.js -o hello.bundle.js --mode development",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.1.1"
  }
}

之后执行:

npm run build

就能完成打包操作。

额外测试提示

你的hello.js里写了alert函数,打包后可以新建一个index.html来测试效果:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Webpack Demo</title>
</head>
<body>
  <script src="./hello.bundle.js"></script>
  <script>
    hello('Hello Webpack!'); // 调用hello函数测试弹窗效果
  </script>
</body>
</html>

打开这个HTML文件就能看到弹窗啦。

内容的提问来源于stack exchange,提问作者fung.dayuer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:54:36