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

React@18+React Router DOM@6与Babel/Webpack路由冲突排查

React Router 非根路径访问出现 Cannot GET /dashboard 错误

使用的库版本

{
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.8.1",
    "@babel/cli": "^7.20.7",
    "@babel/core": "^7.20.12",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^9.1.2"
}

路由组件配置

export default function Routes() {
  return useRoutes([
    {
      path: "auth",
      children: [
        {
          path: "login",
          element: (
            <GuestGuard>
              <Login />
            </GuestGuard>
          ),
        },
      ],
    },
    // 仪表盘路由
    {
      path: "dashboard",
      element: (
        <AuthGuard>
          <Dashboard />
        </AuthGuard>
      ),
    },
    {
      path: "/",
      element: (
        <AuthGuard>
          <Dashboard />
        </AuthGuard>
      ),
    },
    { path: "*", element: <Navigate to="/404" replace /> },
  ]);
}

Main 组件中使用 Routes

const Main = () => {
    return (
        <React.Fragment>
            <Router>
                <Routes />
            </Router>
        </React.Fragment>
    );
}

问题现象

根据路由配置,项目应支持3个可用URL:

  • "/auth/login"
  • "/dashboard"
  • "/"

但访问非根路径(例如/dashboard)时,会收到错误:

Cannot GET /dashboard

这是我首次手动配置 Webpack 和 Babel,推测问题源于此,我的 webpack.config.js 如下:

Webpack 配置

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const dotenv = require('dotenv')

// 从.env文件加载环境变量到process.env
dotenv.config();

module.exports = {
  entry: './index.js',
  mode: 'development',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index_bundle.js',
  },
  target: 'web',
  devServer: {
    port: '3000',
    static: {
      directory: path.join(__dirname, 'public')
    },
    open: true,
    hot: true,
    liveReload: true,
    historyApiFallback: true,
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    alias: {
      process: "process/browser"
    },
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
    ],
  },
  plugins: [
    new webpack.ProvidePlugin({
      process: 'process/browser',
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'public', 'index.html')
    }),
    new webpack.DefinePlugin({
      'process.env': JSON.stringify(process.env)
    })
  ]
};

请问我遗漏了什么配置?

内容的提问来源于stack exchange,提问作者Itzik.B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:31:18