0

我遇到了一个问题,我无法导航到路径大于 1 部分的路由,例如使用时react-router-dom@4.2.2:此外,这是我遇到此问题的存储库的 Github 链接。

https://github.com/ShawnCholeva/React-Typescript-Webpack4-Router

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
//All routes work if I use HashRouter here instead of BrowserRouter

class App extends Component {
    render() {
        return (
            <Router>
                <Switch>
                    <Route exact path='/' component={ Login }/> <--- Works
                    <Route exact path='/accountSetup/:guid?' component={ AccountSetup }/> 
                    ^-- Above works when just '/accountSetup' but fails when I do '/accountSetup/123'
                    <Route component={ NotFound } /> <--- Works
                </Switch>
            </Router>
        );
    }
}

所以我注意到这只有在我使用 HashRouter 而不是 BrowserRouter 时才有效。所以这让我认为这可能是我通过webpack-dev-server@3.1.1. 所以我看到我必须将 historyApiFallback 属性添加到我的 devServer 属性对象中,webpack@4.2.0如下所示:

devServer: {
    compress: true,
    port: 8080,
    historyApiFallback: true,
    contentBase: path.resolve(__dirname),
    publicPath: '/',
}

然后我通过 package.json 中的 npm 脚本运行应用程序,如下所示:

"start": "webpack-dev-server --open --mode development"

因此,当我导航到 localhost:5000/accountSetup/123 时,我在控制台中收到以下错误:

在此处输入图像描述

我还尝试将其与http-server-spa包一起提供,并在导航时注意到以下日志:

[OK] Serving static files from ./dist
[OK] Using the fallback file index.html
[OK] Listening on http://localhost:8080
----------------------------------------------
[OK] GET /accountSetup
[OK] GET /bundle.js
[OK] GET /accountSetup/123
[ER] GET /accountSetup/bundle.js

似乎它正在将最后一个路由参数的url中的前缀添加到路由加载bundle.js中。所以你可以看到当我导航到 accountSetup 时,它只是引用了 bundle.js,因为它是 url 中的最后一段。但是当我添加多个段时,似乎将之前的段从 localhost 附加到最后一个段,到 bundle.js 的路径

编辑:

似乎与使用动态路由的 BrowserRouter 与使用静态路由的 HashRouter 有关。

这是我完整的 package.json 和 webpack.config.js 文件

包.json:

{
  "name": "react-webpack4-typescript-skeleton",
  "version": "1.0.0",
  "description": "React application using Webpack 4 and Typescript",
  "main": "index.tsx",
  "scripts": {
    "start": "webpack-dev-server --open --mode development",
    "prestart": "npm run test",
    "build:prod": "webpack --mode production --config webpack.config.js",
    "lint": "tslint 'src/**/*.{ts,tsx}'",
    "test": "jest",
    "pretest": "npm run lint",
    "build:docker": "docker-compose up --build -d"
  },
  "keywords": [
    "React",
    "Webpack 4",
    "Typescript"
  ],
  "author": "Shawn Choleva",
  "license": "MIT",
  "devDependencies": {
    "@types/jest": "^22.2.2",
    "@types/react": "^16.0.41",
    "@types/react-dom": "^16.0.4",
    "@types/react-redux": "^5.0.15",
    "@types/react-router-dom": "^4.2.5",
    "@types/redux": "^3.6.0",
    "@types/webpack": "^4.1.2",
    "@types/webpack-dev-server": "^2.9.4",
    "css-loader": "^0.28.11",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.1.0",
    "jest": "^22.4.3",
    "less-loader": "^4.1.0",
    "style-loader": "^0.20.3",
    "ts-jest": "^22.4.2",
    "ts-loader": "^4.1.0",
    "tslint": "^5.9.1",
    "tslint-react": "^3.5.1",
    "typescript": "^2.7.2",
    "url-loader": "^1.0.1",
    "webpack": "^4.2.0",
    "webpack-cli": "^2.0.13",
    "webpack-dev-server": "^3.1.1"
  },
  "dependencies": {
    "less": "^3.0.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.2.2",
    "redux": "^3.7.2"
  },
  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

webpack.config.js:

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

const config = {
  entry: './src/index.tsx',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: "style-loader"
          },
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
              modules: true,
              localIdentName: '[local]___[hash:base64:5]'
             }
          },
          {
            loader: "less-loader"
          }
        ]
      },
      { 
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use:'url-loader' 
      },
      { 
        test: /\.(png|jp(e*)g|svg)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 10000,
              name: 'images/[hash]-[name].[ext]',
            },
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: [ '.ts', '.tsx', '.js' ]
  },
  plugins: [
    new HtmlWebpackPlugin({
        title: 'Application Name',
        template: path.join(__dirname, 'src/index.html')
    })
  ],
  devtool: 'inline-source-map',
  devServer: {
    compress: true,
    port: 8080,
    historyApiFallback: true,
    contentBase: path.resolve(__dirname),
    publicPath: '/',
  }
};

module.exports = config;
4

2 回答 2

9

我想我找到了问题所在。您的publicPathwebpack 配置中缺少 。这是更新的输出配置:

output: {
   filename: 'bundle.js',
   path: path.resolve(__dirname, 'dist'),
   publicPath: '/' <-- ADDED THIS
  },
于 2018-04-16T05:14:59.423 回答
1

看起来您正在尝试制作嵌套路线。但是在您指出的使用动态路由的 ReactRouter v4 中,嵌套路由应该嵌套在组件内。AccountSetup您应该在渲染方法中添加含义。

render(){
 //...
  <Route
    path={match.url + '/test'}
    component={Test}
  />
// ...
}

在文档中阅读有关嵌套路由的更多信息。这是一个活生生的例子
如果您确实想使用静态路由,您可以试试这个

于 2018-04-16T04:37:33.867 回答