You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目运行webpack-dev-server出现Cannot GET /错误如何解决?

问题原因

  • 核心原因是webpack.config.js中output.publicPath配置为/build/,webpack-dev-server会将所有构建产物托管在该路径下,根路径/无对应静态资源,因此返回404
  • 存在两处配置错误:
    1. output.path写法错误:path.resolve(__dirname, '/build/')中第二个参数以/开头会被解析为系统根路径,而非项目根目录下的build文件夹
    2. html-webpack-plugin的模板路径配置错误:当前指向构建产物目录build下的index.html,构建前该目录不存在对应模板文件,会导致html生成异常

修复步骤

  1. 调整webpack.config.js配置:
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry: './src/index.tsx',
    devtool: 'eval-source-map',
    // 新增devServer配置
    devServer: {
        historyApiFallback: true, // 适配React Browser路由刷新场景
        open: true, // 启动后自动打开页面
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    module: {
        rules:[
            {
                test: /\.(ts|js)x?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader:'babel-loader',
                    },
                ],
                include:[path.resolve(__dirname, 'src')],
            },{
                test: /\.css$/,
                use:['style-loader', 'css-loader'],
                include:[path.resolve(__dirname, 'src')],
            },{
                test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
                type:'asset/resource',
                include:[path.resolve(__dirname, 'src')],
            },
        ],
    },
    output: {
        publicPath: '/', // 修改为根路径,产物托管在根路径下
        filename: 'bundle.js',
        path: path.resolve(__dirname, './build'), // 修正路径写法,指向项目根目录下的build文件夹
    },
    mode: 'development',
    plugins: [
        new htmlWebpackPlugin({
            // 先将原来build目录下的index.html移动到项目根目录新建的public文件夹中,再修改此处路径
            template: path.resolve(__dirname, 'public', 'index.html')
        }),
    ],
}
  1. 调整项目文件结构:在项目根目录新建public文件夹,将原build目录下的index.html移动到public文件夹中
  2. 重新执行npm run serve启动项目,访问http://localhost:8080即可正常加载页面

内容的提问来源于stack exchange,提问作者Octopus-Charm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:36:04