遵循文档 here (Building for Relative Paths) ,因此在 package.json 中设置 homepage 字段不会在构建期间设置 PUBLIC_URL。
预期行为 %PUBLIC_URL%
在 build/index.html
应替换为在 package.json 的主页字段中设置的 URL。
package.json:
"homepage": "https://example.com",
构建/index.html:
<script type="text/javascript" src="https://example.com/static/js/main.ec7f8973.js">
实际行为
<script type="text/javascript" src="/static/js/main.ec7f8973.js">
%PUBLIC_URL%
将被替换为空。
最佳答案
在 package.json 中设置 homepage 字段后,生成构建时会显示以下消息:
The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.
The build folder is ready to be deployed.
这导致您的 实际行为 .
我需要有一个完整的元标签 URL,例如 og:image 和 twitter:image:src
如 Timer said :“除非您明确使用 PUBLIC_URL 环境变量,否则只会将 URL 的路径插入到 %PUBLIC_URL% 中。”
所以我创建了一个 .env 在我的应用程序的根目录中添加一个引用包主页中相同 url 的变量的文件:
REACT_APP_BASE_URL=https://example.com
在 index.html 中,我将 %PUBLIC_URL% 替换为 env 变量:
<meta property="og:image" content="%REACT_APP_BASE_URL%/img/facebook_1200x630.jpg" />
以及构建的结果:
<meta property="og:image" content="https://example.com/img/facebook_1200x630.jpg" />
我相信这就是你所需要的。
关于reactjs - 在 package.json 中设置主页不会在构建时设置 PUBLIC_URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043369/