使用相对路径部署反应路由器 [英] React Router with relative path deployment
问题描述
我的问题是关于 react-router-dom
与部署到相对路径的结合(请参阅 https://create-react-app.dev/docs/deployment#building-for-relative-paths).在我的开发环境中,路由器工作正常,但是一旦我使用 package.json
中设置的 homepage
标记构建和部署我的应用程序,路由器似乎不再工作了.
首先,我认为它会起作用.毕竟,这是一个构建选项,通过 react 为特定 url 构建构建,我会假设该相对路径具有相同的功能.然而,<Link to="">
部分和
都不尊重我的反应应用程序的相对路径.
其次,我还没有找到规避这种行为的解决方案.有什么想法吗?
处理反应路由器和相对路径的其他问题集中在一个完全不同的主题上.所以我还没有找到我的问题的答案.这个 React-router 应用部署在不同的位置(子目录)可能正在接近,可能是一种解决方法.
信息:
"react-dom": "^16.8.6","react-router-dom": "^5.0.1",
编辑和 PS:
我可能只需要设置一个基本名称.如果 basename 正在更改,我至少想从 package.json
中的设置推断它,而不是根据某些 package.json
设置更改我的代码.>
编辑 2:
我可以使用 basename={process.env.PUBLIC_URL}
将 basename 设置为正确的 URL.然而,路线仍然不匹配.然而,这些链接似乎没有问题,所以 实际上会导致链接到
{process.env.PUBLIC_URL}/xx
这是所需的行为,但路由器
与它们不匹配. 实际上这就是答案,您可以从头开始.
使用 basename={process.env.PUBLIC_URL}
确实解决了我的问题.
致任何遇到相同问题的人:阅读我原始问题中的编辑内容.使用 basename={process.env.PUBLIC_URL}
确实解决了我的问题.
My question is concerning the react-router-dom
in conjunction with deployment to a relative path (see https://create-react-app.dev/docs/deployment#building-for-relative-paths). On my dev environment the router is working fine, but once i build and deploy my application with the homepage
tag set in package.json
the router does not seem to work anymore.
First of all i would assume that it would be working. After all it's a build option by react to make a build for a specific url and i would assume the same functionality with that relative path in place. However neither the <Link to="">
parts nor the <Switch>
do respect the relative path of my react app.
Second of all i have not found a solution to circumvent this behavior. Any ideas?
Other question dealing with react router and relative paths are focusing on a totally different topic. So i have not found an answer to my question. This React-router app deployed on different locations (subdirectories) is maybe getting close and could be a way to deal with that.
For info:
"react-dom": "^16.8.6",
"react-router-dom": "^5.0.1",
EDIT and PS:
I would probably just need to set a basename. If the basename is changing i would at least want to infer it from the setting in the package.json
and not change my code depending on some package.json
setting.
EDIT 2:
I could use basename={process.env.PUBLIC_URL}
to set the basename to the correct URL. However the routes are still not matching. The links however appear to be fine, so <Link to="/xx">
would actually result in an link to {process.env.PUBLIC_URL}/xx
which is the desired behavior, but the routers <Switch>
does not match them. Actually this is the answer and you can scratch that.
Using basename={process.env.PUBLIC_URL}
does solve my problem.
To anyone stumbling across the same problem: Read the edits in my original question. Using basename={process.env.PUBLIC_URL}
does solve my problem.
这篇关于使用相对路径部署反应路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!