【发布时间】:2018-06-22 09:38:40
【问题描述】:
This SO thread 解释了如何捆绑 React 应用程序以部署到 Web 服务器上的特定子目录。我想将我的 react 应用程序捆绑到我的网络服务器上的 any 子目录中。换句话说:是否可以构建一个反应应用程序,以便我可以将它从
到
或
不重建或改变任何东西?
【问题讨论】:
标签: reactjs deployment build
This SO thread 解释了如何捆绑 React 应用程序以部署到 Web 服务器上的特定子目录。我想将我的 react 应用程序捆绑到我的网络服务器上的 any 子目录中。换句话说:是否可以构建一个反应应用程序,以便我可以将它从
到
或
不重建或改变任何东西?
【问题讨论】:
标签: reactjs deployment build
如果你使用 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>
【讨论】:
"homepage": "." 时,您的示例中的生产应用程序版本是如何构建的?如果我没记错的话,那么最初的问题是要求不必为特定路径构建生产应用程序。
在 package.json 中
"homepage": ".",
【讨论】:
这个问题和类似问题的答案似乎忽略了这一点,如果使用客户端路由(如 React 路由器),则在从子目录提供服务时应该进行一些后端更改。
有几种方法可以解决这个问题。一种是使用<HashRouter>;这种方法在here 或 React Router 文档中都有很好的描述。
另一种方法是将<BrowserRouter> 与 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 查看上述示例。
【讨论】: