如果不在 URL 中添加 index.html,React 构建将无法正常工作
P粉216203545
P粉216203545 2023-09-01 11:25:58
[React讨论组]
<p>我正在使用哈希路由来处理 React JS 应用程序。在本地环境中应用程序运行良好。</p> <p>例如https://stackoverflow.com/posts/ 应该是应用程序的 URL,但它不起作用,我必须使用 https://stackoverflow.com/posts/index.html 才能使其工作。</p> <p>部署后,我发现它正在下载名为“<strong>download</strong>”的空文件,而不是提供构建文件中预设的<strong>index.html</strong>文件。为了在服务器上运行构建,我使用 S3 和 CloudFront 架构。</p> <p>现在,我无法确定 HASH 路由是否行为错误或者 AWS 部署出现问题。</p> <p>使用 React JS 的代码片段</p> <pre class="brush:php;toolbar:false;">import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './redux/store'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { HashRouter } from 'react-router-dom/cjs/react-router-dom'; ReactDOM.render( &lt;Provider store={store}&gt; &lt;HashRouter&gt; &lt;App /&gt; &lt;/HashRouter&gt; &lt;/Provider&gt; document.getElementById('root') );</pre> <p><strong>部分package.json内容</strong></p> <pre class="brush:php;toolbar:false;">{ &quot;name&quot;: &quot;loremipsum&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;homepage&quot;: &quot;/loremipsum/&quot; }</pre></p>
P粉216203545
P粉216203545

全部回复(1)
P粉515066518

是否需要部署在子目录上?如果是,您将必须更改 package.json 文件的内容,以强制相对于 index.html 文件提供资源。

{
  "name": "loremipsum",
  "version": "0.1.0",
  "private": true,
  "homepage": ".",
  "scripts": {
    "build": "react-scripts build",
    "build-prd": "PUBLIC_URL=http://www.foo/relativepath react-scripts build"
    // ...
  }
}

有了这个,我们将能够将托管在 http://www.foo 中的应用程序移动到 http://www.foo/relativepath 甚至https://www.foo/bar1/bar2/ 无需重建。

您还必须覆盖 PUBLIC_URL 以包含您想要托管文件的域和子目录

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号