在 package.json 中设置主页不会在构建时设置 PUBLIC_URL

rah*_*hul 4 reactjs webpack package.json

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

预期行为

%PUBLIC_URL%inbuild/index.html应替换为在 package.json 的主页字段中设置的 URL。

包.json:

"homepage": "https://example.com",
Run Code Online (Sandbox Code Playgroud)

构建/index.html:

<script type="text/javascript" src="https://example.com/static/js/main.ec7f8973.js">
Run Code Online (Sandbox Code Playgroud)

实际行为

<script type="text/javascript" src="/static/js/main.ec7f8973.js">
Run Code Online (Sandbox Code Playgroud)

%PUBLIC_URL% 将被替换为空。

小智 6

在 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.
Run Code Online (Sandbox Code Playgroud)

这导致您的实际行为。

我需要有一个完整的元标签 URL,例如og:image和twitter:image:src

正如计时器所说:“只有 URL 的路径被插入到 %PUBLIC_URL% 中,除非您明确使用 PUBLIC_URL 环境变量。”

因此,我在应用程序的根目录中创建了一个.env文件,并在包的主页中添加了一个引用相同 url 的变量:

REACT_APP_BASE_URL=https://example.com
Run Code Online (Sandbox Code Playgroud)

在 index.html 中,我将 %PUBLIC_URL% 替换为 env 变量:

<meta property="og:image" content="%REACT_APP_BASE_URL%/img/facebook_1200x630.jpg" />
Run Code Online (Sandbox Code Playgroud)

以及构建的结果:

<meta property="og:image" content="https://example.com/img/facebook_1200x630.jpg" />
Run Code Online (Sandbox Code Playgroud)

我相信这就是你所需要的。