Webpack DevServer返回目录列表而非main.html问题排查求助
问题根因
你配置的HtmlWebpackPlugin生成的HTML文件名为main.html,而webpack-dev-server默认会自动加载静态资源根目录下的index.html作为访问根路径时的默认页面,找不到对应文件就会返回目录列表。另外你当前的devServer配置是webpack 4的语法,如果使用的是webpack 5版本也会出现配置失效问题。
解决方案
- 方案1(推荐):修改
HtmlWebpackPlugin的filename配置为index.html
plugins: [new HtmlWebpackPlugin({ filename: "index.html", template: path.resolve(__dirname, "src/index.html"), }), // 其余插件配置保持不变 ]
- 方案2:如果需要保留HTML文件名为
main.html,可在devServer配置中指定默认打开的页面名:
若使用webpack 4,修改配置如下:
若使用webpack 5,原devServer的devServer: { publicPath: "/", contentBase: path.resolve(__dirname, "./dist"), port: 5001, open:true, hot: true, watchContentBase: true, index: 'main.html' // 新增该行配置 },contentBase、watchContentBase配置已废弃,需更新为:devServer: { publicPath: "/", static: path.resolve(__dirname, "./dist"), port: 5001, open:true, hot: true, watchFiles: true, index: 'main.html' },
修改完成后重启webpack-dev-server即可正常加载预期的HTML页面。
内容的提问来源于stack exchange,提问作者bunee
相关产品推荐
相关产品推荐

