本文介绍了在 package.json 中使用“主页",不会弄乱本地主机的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题实际上直接来自我对上一个问题的答案.

This question actually follows directly from my answer on a previous question.

我在我的 package.json 中添加了一个 "homepage" 因为它是我在 Github Pages 上托管的 React 应用程序.npm run build 的输出表明现在可以部署 /build 目录,并且假设项目托管在 /project_name/.

I added a "homepage" to my package.json because it is a React app that I hosted on Github Pages. The output of npm run build say that the /build directory can now be deployed, and it assumes the project is being hosted at /project_name/.

但是在本地主机上,该项目不是托管在 /project_name/,因此为 js 和 css 请求的路径搞砸了(寻找 /project_name/static/... 而不是 /static/...) 并且应用程序损坏了.

But on localhost, the project is not being hosted at /project_name/, so the paths being requested for js and css are messed up (looking for /project_name/static/... instead of /static/...) and the app broken.

如何在 package.json 中包含 homepage 字段,以便他们可以部署到 Github Pages(例如),同时仍然使用可运行的应用程序在本地进行开发?

How can one have the homepage field in package.json so that they can deploy to Github Pages (for example) while still develop locally with a working app?

推荐答案

文档create-react-app 解释了如何从不同的相对路径提供相同的构建.

Docs for create-react-app explains how to serve same build from different relative paths.

如果你把主页设为

"homepage": ".",

资产将相对于 index.html 提供.然后您就可以将您的应用从 http://mywebsite.com 移动到 http://mywebsite.com/relativepath 甚至 http://mywebsite.com/relative/path 无需重新构建.

assets will be served relative to index.html. You will then be able to move your app from http://mywebsite.com to http://mywebsite.com/relativepath or even http://mywebsite.com/relative/path without having to rebuild it.

出于开发目的,使用 yarn startnpm start 服务就足够了.应用程序将在 localhost 中可用

For development purposes, serving using yarn start or npm start is good enough. App will be available in localhost

这篇关于在 package.json 中使用“主页",不会弄乱本地主机的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 10:52