'Setting homepage in package.json doesn't set PUBLIC_URL on build

Following the docs here (Building for Relative Paths), so setting homepage field in package.json doesn't set PUBLIC_URL during the build.

Expected behavior

%PUBLIC_URL% in build/index.html should be replaced with URL set in package.json's homepage field.

package.json:

"homepage": "https://example.com",

build/index.html:

<script type="text/javascript" src="https://example.com/static/js/main.ec7f8973.js">

Actual behavior

<script type="text/javascript" src="/static/js/main.ec7f8973.js">

%PUBLIC_URL% will be replaced with nothing.



Solution 1:[1]

After setting homepage field in package.json the following message is displayed when you generate your build:

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.

Which leads to your Actual Behavior.

I had the need to have a full URL for the meta tags such as og:image and twitter:image:src

As Timer said: "Only the path of the URL is interpolated into %PUBLIC_URL%, unless if you explicitly use the PUBLIC_URL environment variable."

So I create an .env file at the root directory of my application adding a variable referencing the same url in package's homepage:

REACT_APP_BASE_URL=https://example.com

In index.html I replaced the %PUBLIC_URL% for the env variable:

<meta property="og:image" content="%REACT_APP_BASE_URL%/img/facebook_1200x630.jpg" />

And the result of the build:

<meta property="og:image" content="https://example.com/img/facebook_1200x630.jpg" />

Which I believe is what you need.

Solution 2:[2]

I had a similar scenario with the OP and this solution from Github worked for me: https://github.com/facebook/create-react-app/issues/2575#issuecomment-452295290

In your environment variable file (e.g., .env) simply set PUBLIC_URL as follows:

PUBLIC_URL="https://example.com"

This will yield the results as follows when you build your project:

<script type="text/javascript" src="https://example.com/static/js/main.ec7f8973.js">

I have tested this using a production .env.production environment variable file so I do not know if assigning PUBLIC_URL in a generic .env will break local dev environment.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kratka
Solution 2 95faf8e76605e973