使用webpack-dev-server报404错误,但打包后运行正常的原因排查
Webpack Dev Server 404 错误排查与解决
问题场景
执行webpack-dev-server --open --config webpack.dev.js时出现Failed to load resource: the server responded with a status of 404 (Not Found)错误,但执行webpack --config webpack.prod.js打包后打开index.html可正常运行。
项目index.html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./src/css/style.css"> </head> <body> <div class="container"> <button id="displayNumber">Show/Change Number</button> <span id="number">15</span> </div> <script src="./dist/bundle.js"></script> </body> </html>
Webpack配置文件webpack.config.js代码
var path = require('path'); module.exports = { mode: 'development', entry: path.resolve(__dirname,'src/js/script.js'), output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: 'dist' }, devServer: { static: { directory: path.resolve(__dirname,'dist'), publicPath: '/dist/', }, open: true, hot: true, } }
错误原因
- dev-server内存打包特性冲突:webpack-dev-server不会将打包产物写入本地
dist目录,而是存在内存中。但你的index.html直接引用了本地的./dist/bundle.js,服务器找不到对应资源。 - 静态资源目录配置错误:dev-server的
static.directory只指向了dist目录,无法访问根目录的index.html和src目录下的CSS文件,导致这些资源也出现404。 - publicPath格式不一致:
output.publicPath设为dist(相对路径),而devServer.static.publicPath设为/dist/(绝对路径),路径解析规则混乱,加剧资源定位失败。
修复方案
方案一:调整devServer静态资源配置(快速修复)
修改webpack.config.js,让devServer能访问项目根目录的所有文件,并统一路径规则:
module.exports = { // ...其他配置 output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/dist/' // 修改为带斜杠的绝对路径格式 }, devServer: { static: { directory: path.resolve(__dirname), // 指向项目根目录,覆盖原dist目录配置 publicPath: '/', }, open: true, hot: true, } }
方案二:使用html-webpack-plugin自动生成页面(推荐)
该插件会自动处理资源引用,彻底避免路径错误:
- 安装插件:
npm install html-webpack-plugin --save-dev
- 修改
webpack.config.js:
var path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { // ...其他配置 output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/' }, plugins: [ new HtmlWebpackPlugin({ template: './index.html', // 以现有index.html为模板 inject: 'body' // 自动将bundle.js注入到body底部 }) ], devServer: { static: { directory: path.resolve(__dirname, 'dist'), publicPath: '/', }, open: true, hot: true, } }
- 删除
index.html中手动添加的<script src="./dist/bundle.js"></script>,插件会自动完成资源注入。
额外优化:统一处理CSS资源
当前index.html直接引用src/css/style.css,建议改为在入口JS中引入,让webpack统一处理:
- 在
src/js/script.js中添加:
import '../css/style.css';
- 安装CSS处理loader:
npm install css-loader style-loader --save-dev
- 在
webpack.config.js中添加module规则:
module.exports = { // ...其他配置 module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] // 依次解析CSS并注入页面 } ] } }
之后删除index.html中的<link rel="stylesheet" href="./src/css/style.css">即可。
内容的提问来源于stack exchange,提问作者Aezz
相关产品推荐
相关产品推荐

