Webpack搭配express中间件启动项目无法访问index.html问题排查
问题原因
- devServer配置无效:你当前使用自定义Express + webpack-dev-middleware的方案启动服务,webpack.config中的devServer配置是为webpack-dev-server工具准备的,对自定义Express服务完全不生效,你配置的contentBase自然没有作用。
- publicPath配置错误:output.publicPath设置为
.(相对路径),webpack-dev-middleware会将编译后的资源挂载到相对路径下,而不是服务根路径,所以无法通过根路径访问对应资源。 - HtmlWebpackPlugin模板路径错误:你将template配置为dist目录下的html文件,但dist是webpack的输出目录,编译时会先清空dist目录(你配置了
clean: true),会导致模板文件找不到,最终内存中不会生成对应的html资源。 - Express缺少默认页路由配置:webpack-dev-middleware默认不会处理根路径
/的请求,没有配置默认返回index.html的话,访问根路径就会返回404。
解决方法
第一步:修改webpack.config.js配置
module.exports = { // 其余配置保持不变 output: { filename: 'bundle.[name].js', path: path.resolve(__dirname, './dist'), clean: true, publicPath: '/', // 将相对路径'.'改为根路径'/' assetModuleFilename: 'assets/[name][ext][query]', }, plugins: [ new HtmlWebpackPlugin({ title: 'Index', filename: 'index.html', template: './src/templates/index.html', // 模板路径改为src下的源模板文件 chunks: ['index'], }), new HtmlWebpackPlugin({ title: 'about', filename: 'about.html', template: './src/templates/about.html', // 模板路径改为src下的源模板文件 chunks: ['about'], }), ], // 不需要用到webpack-dev-server的话,devServer配置段可以直接删除 }
第二步:修改server.js配置
const express = require('express'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const app = express(); const config = require('./webpack.config.js'); const compiler = webpack(config); app.use( webpackDevMiddleware(compiler, { publicPath: config.output.publicPath, index: 'index.html' // 新增配置:根路径默认返回index.html }) ); // 可选新增:支持不带后缀访问页面,比如访问/about直接返回about.html app.use((req, res, next) => { if (req.accepts('html') && !req.path.includes('.')) { req.url += '.html'; } next(); }); app.listen(3000, function () { console.log('Example app listening on port 3000!\n'); });
修改完成后重启服务即可正常访问:
- 访问
localhost:3000直接进入首页 - 访问
localhost:3000/about进入关于页 - 访问
localhost:3000/index.html、localhost:3000/about.html也可正常返回对应页面
内容的提问来源于stack exchange,提问作者michaelT
相关产品推荐
相关产品推荐

