我需要在 servlet 环境中部署 React 应用程序作为部署在 tomcat 容器中的 war 。
到目前为止我执行的步骤:
1) 运行:> npm run build
2) 将构建目录的内容放在我的 war 下的 WebContent > dist 文件夹下,如下所示:
3) 在 WebContent 下添加了一个 index.html,重定向到 dist 文件夹内的索引:
<body onLoad="window.location.href='./dist'">
部署 war 时执行重定向,浏览器将我带到这个位置: http://localhost:8080/MyApp/dist/
但是页面出现错误:
(“dist > static”文件夹下有js文件的链接,但是url中没有/MyApp/所以找不到)
尝试了什么:
1) 点击此链接:https://www.megadix.it/blog/create-react-app-servlet/ 我尝试将 BrowserRouter 的基本名称设置为:
import {BrowserRouter as Router, Route, Switch, Redirect} from "react-router-dom";
ReactDOM.render(
<div>
{/*<Router basename={process.env.REACT_APP_ROUTER_BASE || ''}>*/}
<Router basename='/MyApp'>
<Switch>
<Route path="/" exact component={App} />
<Route path="/login" component={Login} />
<Route path="/customize" component={ProjectCustomize} />
{/*<Redirect path="*" to="/" />*/}
</Switch>
</Router>
{/*<Login />*/}
{/*<App/>*/}
</div>,
document.getElementById('root'));
但是没有生效!
2) 关注此问题:https://github.com/coryhouse/react-slingshot/issues/397 我编辑了我的 public/index.html ohave "."在 %PUBLIC_URL% 之前:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href=".%PUBLIC_URL%/tdf.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href=".%PUBLIC_URL%/manifest.json" />
似乎我通过了 *.js 文件加载错误,现在加载 css 时遇到问题:
注意事项
即使我手动编辑链接并尝试访问该站点,也没有错误,但没有显示任何内容!
如果我运行“serve -s build”(通常情况下,没有 war ),它会起作用!
最佳答案
在你的 React 项目中打开 package.json 文件
添加一个键值,即 "homepage":"./"。它看起来像
{
"name": "your-app-name",
"version": "0.1.0",
"private": true,
"homepage": "./"
.
.
.
}
现在运行 => npm run build 并按照与您相同的步骤操作。
关于reactjs - 在 Servlet 环境中部署 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770197/