Webpack Dev Server访问localhost:5000无法加载根目录index.html如何解决
问题原因
你的Webpack Dev Server静态资源服务目录仅配置了dist文件夹,而index.html存放在项目根目录,不在服务器的静态资源检索范围内,因此访问localhost:5000时无法匹配到该文件返回。
另外你当前配置中output.path的写法存在错误,path.resolve(__dirname + 'dist')应修改为path.resolve(__dirname, 'dist'),否则会生成错误的输出路径。
最优解决方案:使用
html-webpack-plugin 这是Webpack生态处理HTML资源的标准最佳实践,配置后可以自动处理HTML的生成与资源注入:
- 首先安装依赖:
npm install html-webpack-plugin -D
- 修改
webpack.dev.js配置,新增插件配置:
const path = require('path'); // 引入插件 const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/app/app.js', output: { filename: 'main.js', // 修正路径写法 path: path.resolve(__dirname, 'dist'), }, devServer: { static: { directory: path.join(__dirname, 'dist'), }, port: 5000, open: true, }, // 新增插件配置 plugins: [ new HtmlWebpackPlugin({ // 指定根目录下的index.html为模板 template: path.resolve(__dirname, 'index.html') }) ] };
该方案的优势:插件会自动将根目录的index.html作为模板复制到dist目录,同时自动把打包生成的main.js注入到HTML的<script>标签中,不需要手动维护JS引用路径,同时兼容开发与生产打包的流程。
临时调试方案(不推荐长期使用)
如果仅需要快速验证效果不想安装插件,可以直接修改devServer.static配置,将项目根目录加入静态服务范围:
devServer: { static: [ path.join(__dirname, 'dist'), // 新增根目录作为静态资源目录 __dirname ], port: 5000, open: true, }
该方案需要你手动在根目录的index.html中引入/main.js,路径容易出错,且不符合生产打包的规范,仅适合临时测试使用。
内容的提问来源于stack exchange,提问作者hubvill
相关产品推荐
相关产品推荐

