我用 create-react-app 构建了一个小型 React 应用程序,它在运行 npm start
后在本地服务器上运行良好。到目前为止还可以。
但是,当我运行 npm run build
时,该过程似乎可以正确执行(创建构建文件夹,其中包含捆绑的 js 文件和 index.html 文件),但是当我打开 index.html 时html 在我的浏览器中它什么也不呈现。我错过了什么?
除此之外:我还尝试将其上传到远程服务器,当我访问 URL 时,浏览器返回...
Forbidden: You don't have permission to access / on this server.
...如果有人知道如何解决这个问题,我也将不胜感激。
最佳答案
However, when I run npm run build, the process appears to execute correctly (creates build folder, which contains the bundled js file and the html.index file), but when I open index.html in my browser it renders nothing. What am I missing?
当你运行 npm run build
时,它会打印相关的指令:
您不能只打开 index.html
,因为它应该使用静态文件服务器提供服务。
这是因为大多数 React 应用程序都使用客户端路由,而您不能使用 file://
URL 来做到这一点。
在生产中,您可以使用 Nginx、Apache、Node(例如 Express)或任何其他服务器来提供静态 Assets 。只要确保如果您使用客户端路由,您为任何未知请求提供 index.html
,例如 /*
,而不仅仅是 /
.
在开发中,您可以为此使用 pushstate-server
。它适用于客户端路由。这正是打印说明建议您执行的操作。
I also tried uploading it to a remote server and when I went to the URL the browser came back with Forbidden: You don't have permission to access / on this server.
您需要上传 build
文件夹的内容,而不是 build
文件夹本身。否则服务器找不到你的index.html
,因为它在build/index.html
里面,所以它失败了。如果您的服务器未检测到顶级 index.html
,请参阅您的服务器的文档以配置默认提供的文件。
https://stackoverflow.com/questions/39791069/