【问题标题】:Setting homepage in package.json doesn't set PUBLIC_URL on build在 package.json 中设置主页不会在构建时设置 PUBLIC_URL
【发布时间】:2018-10-07 04:13:10
【问题描述】:

遵循文档here (Building for Relative Paths),因此在 package.json 中设置主页字段不会在构建期间设置 PUBLIC_URL。

预期行为

build/index.html 中的%PUBLIC_URL% 应替换为 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% 将被替换为空。

【问题讨论】:

标签: reactjs webpack package.json


【解决方案1】:

在 package.json 中设置主页字段后,生成构建时会显示以下消息:

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:imagetwitter:image:src

As Timer said:“只有 URL 的路径被插入到 %PUBLIC_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 的 public/index.html 中使用 .env 变量,所以谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2011-09-21
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多