【问题标题】:Can I host the same react app at two different paths on my website?我可以在我的网站上的两个不同路径上托管相同的 React 应用程序吗?
【发布时间】:2019-08-15 17:10:09
【问题描述】:

我目前的设置

为此,我已经在我的 package.json 中设置了

"homepage": "https://example.com/register/"

在我的 App.js 上

<Router history={history} basename="/register">
</Router>

我的 NGINX 看起来像这样:

server {
    listen 5400;
    access_log /var/log/nginx/wordpress-access.log;
    error_log /var/log/nginx/wordpress-error.log;
    location / {
        root /home/ubuntu/...../build/;
        index index.html;
        expires 1d;
        try_files $uri /index.html;
    }

}


server {
    listen 443 ssl;
    listen [::]:443;
    index  index.php index.html index.htm;
    server_name  example.com;
    location / {
        ... old setup
    }
    location /register {
         proxy_pass http://127.0.1.1:5400/;
    }
}

这就是我想要做的。我想在 url example.com/pricing 上托管相同的 React 应用程序。

我怎样才能做到这一点?我希望代码/逻辑等的重复最少。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    一种解决方案是进行两个单独的构建,一个用于/register,一个用于/pricing

    除了使用package.json 中的homepage 字段来指定根,您可以使用环境变量PUBLIC_URLadd a custom environment variable,例如调用REACT_APP_BASENAME 用于 basenameRouter 属性。

    <Router history={history} basename={process.env.REACT_APP_BASENAME}>
    

    您的构建脚本可能如下所示:

    "build:register": "PUBLIC_URL=https://example.com/register/ REACT_APP_BASENAME=/register node scripts/build.js",
    "build:pricing": "PUBLIC_URL=https://example.com/pricing/ REACT_APP_BASENAME=/pricing node scripts/build.js"
    

    【讨论】:

      【解决方案2】:

      这可能不适用于您的特定设置,但 react-router v5 有一个新功能,允许同一组件有多个匹配器:

      // Instead of this:
      <Switch>
        <Route path="/users/:id" component={User} />
        <Route path="/profile/:id" component={User} />
      </Switch>
      
      // you can now do this:
      <Route path={["/users/:id", "/profile/:id"]} component={User} />
      

      https://reacttraining.com/blog/react-router-v5/#new-features

      【讨论】:

      • 感谢您的回答。我知道这一点,但在我的情况下它不起作用,因为我在不同位置与现有网站一起使用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 2015-06-29
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多