【问题标题】:How to setup react-router to work on localhost and deployment URL under path如何设置 react-router 在 localhost 和路径下的部署 URL 上工作
【发布时间】:2017-09-12 23:07:21
【问题描述】:

我正在使用 webpack-dev-serverlocalhost:1111 上本地托管一个 repo。我们已经设置了 Jenkins,以便在任何分支上推送到这个 repo 都可以在jenkins.example.com/repo/branch/ 之类的 url 上查看。我现在正在尝试使用react-router 设置路由

import { Router, Route, Link } from "react-router-dom";
import createBrowserHistory from "history/createBrowserHistory";
const history = createBrowserHistory();

并且正在渲染

<Router history={history}>
  <div>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/Example">Example</Link>
    </nav>
    <Route exact path="/" render={Home} />
    <Route path="/Example" render={Example} />
  </div>
</Router>

这可以按预期在 localhost 上运行。 localhost:1111/Example 呈现 Example。但是&lt;Link to="/Example"&gt; 链接到jenkins.example.com/Example 那里。使用./Example 根本不起作用。如何设置react-router,使其继续在本地以localhost:1111/Example 工作,但使用jenkins.example.com/repo/branch/Example 之类的URL?

【问题讨论】:

  • 将绑定更改为使用 0.0.0.0 而不是 localhost?这只是一个猜测。否则,作为 webpack 构建的一部分,你必须确定你的 IP 并使用它来启动。
  • 如何更改绑定?这是什么意思?
  • 请使用Link组件显示您的代码
  • @GProst 更新为包含 Link 用法:)

标签: reactjs react-router webpack-dev-server react-router-dom


【解决方案1】:

您可以使用&lt;Router&gt;basename 属性来解决这个问题。因此,对于您的 Jenkins 服务器,您必须定义 basename = '/repo/branch' 并且路由器将按预期工作。

但问题是如何为您的路由器动态设置basename。因为今天你使用 Jenkins,明天 localhost 和后天它是生产服务器。

对于这个特殊问题,您可以使用自定义环境变量(例如MY_APP_ROUTER_BASENAME)并通过webpack.DefinePlugin 将其传递给生成的应用程序构建,如下所示:

// in your webpack.config.js

// get basename from your custom environment variable
const routerBasename = process.env.MY_APP_ROUTER_BASENAME

const config = {
  ...
  plugins: [
    ...
    new webpack.DefinePlugin({
      process: {
        env: {
          ROUTER_BASENAME: JSON.stringify(routerBasename)
        }
      }
    }),
    ...
  ],
  ...
}

module.exports = config

然后在您的应用代码库中,您可以像这样获得这个变量:

// also set default value (for using at localhost for example)
const basename = process.env.ROUTER_BASENAME || '/'

...

<Router history={history} basename={basename}>
  ...
</Router>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 2022-12-20
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多