webpack项目运行index.html提示ERR_FILE_NOT_FOUND找不到bundle.js如何解决
问题原因
- 路径不匹配:
index.html存放在src目录下,webpack配置指定打包生成的bundle.js输出到项目根目录的build目录下,你在index.html中写的相对路径bundle.js只会在src目录下查找对应文件,自然会报错找不到。 - 你当前的配置没有配置webpack打包命令,无法正常执行打包操作。
- 额外补充:
link标签引入的style.css如果后续需要经过webpack打包,当前写法也会失效。
修复方案
方案一:标准项目配置(推荐)
这是webpack项目的常规做法,自动处理静态资源路径和文件生成:
- 安装
html-webpack-plugin插件,用于自动生成html文件并注入打包后的资源引用:
npm install html-webpack-plugin --save-dev
- 修改
package.json的scripts字段,新增打包命令:
{ "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --mode production" } }
- 修改
webpack.config.js配置:
const path = require("path"); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: "./src/app.js", output: { filename: "bundle.js", path: __dirname + "/build", clean: true // 每次打包前自动清空build目录旧文件 }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' // 以src下的index.html为模板生成最终html }) ] };
- 执行
npm run build打包,打包完成后直接打开build目录下的index.html即可正常运行,无需手动修改路径。
方案二:临时修改路径测试
如果仅做简单测试不想安装额外插件的话,直接修改src/index.html中的script标签路径即可:
<script src="../build/bundle.js"></script>
修改后先执行打包命令,再直接打开src目录下的index.html即可正常加载到bundle.js文件。
内容的提问来源于stack exchange,提问作者patatafly
相关产品推荐
相关产品推荐

