【问题标题】:How to bundle a React app to work in ANY subdirectory on a server?如何捆绑 React 应用程序以在服务器上的任何子目录中工作?
【发布时间】:2018-06-22 09:38:40
【问题描述】:

This SO thread 解释了如何捆绑 React 应用程序以部署到 Web 服务器上的特定子目录。我想将我的 react 应用程序捆绑到我的网络服务器上的 any 子目录中。换句话说:是否可以构建一个反应应用程序,以便我可以将它从

http://server/foo

http://server/bar

http://server/foo/bar

不重建或改变任何东西?

【问题讨论】:

    标签: reactjs deployment build


    【解决方案1】:

    如果你使用 react-router-dom,如果你知道你的目录名,你可以在路由器中将 basename 设置为“/directory-name”

    如果要将基本名称设置为动态,请使用

    (注意:如果您使用子路由,这将无用)

    在子路由的情况下,为您的路由设置一个标准字符串

    例子:

     let basename_path = null;
       var url = window.location.pathname.toLowerCase();
       if(url.indexOf("react") === -1){    // If string(react) not available
                basename_path = "/";
       }
        else{
           var array = url.split("react");
           basename_path = array[0]+"react/";
         }
    
    
     <Router basename={basename_path}>   
       <Route exact path="/react/home" component={home}/>
       <Route exact path="/react/contactus" component={contactus}/>
       <Route exact path="/react/aboutus" component={aboutus}/>               
     </Router> 
    

    【讨论】:

    • 当使用 CRA(创建 React 应用程序),使用 "homepage": "." 时,您的示例中的生产应用程序版本是如何构建的?如果我没记错的话,那么最初的问题是要求不必为特定路径构建生产应用程序。
    【解决方案2】:

    在 package.json 中

    "homepage": ".",
    

    【讨论】:

    • 请描述为什么我们需要添加相同的内容。
    • 很遗憾,如果您使用的是客户端路由,此解决方案将不起作用。
    【解决方案3】:

    这个问题和类似问题的答案似乎忽略了这一点,如果使用客户端路由(如 React 路由器),则在从子目录提供服务时应该进行一些后端更改。

    有几种方法可以解决这个问题。一种是使用&lt;HashRouter&gt;;这种方法在here 或 React Router 文档中都有很好的描述。

    另一种方法是将&lt;BrowserRouter&gt; 与 Express 一起使用。步骤如下:

    在您的应用中:

        <BrowserRouter basename={process.env.PUBLIC_URL}>
            <Route path="/your_route">
              ...
            </Route>
            <Route exact path="/">
              ...
            </Route>
        </BrowserRouter>
    

    然后,在package.json 中,添加:

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

    (请注意,如果您使用的是客户端路由,“.”将不起作用。)

    然后,在 Express 中,尝试使用 connect-history-api-fallback 包(在 Vue Router 文档中推荐)。

    const express = require('express');
    const historyFallback = require('connect-history-api-fallback');
    
    const app = express();
    app.use(historyFallback);
    
    

    没有这个,用户将无法在浏览器的url栏中直接输入https://example.com/mySubdirectory/my_route;他们会收到cannot GET 错误。

    您可以使用 Apache here 查看上述示例。

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 2021-12-04
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多