Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting base href using Environment variables

Need to set the href value for <base href=""/> tag based on build environment configuration.

Eg:

Staging should have <base href="/staging" />

Prod should have <base href="/" />

Current setup:

Build command:

"build": "sh -ac '. .env.${REACT_APP_ENV}; react-scripts build'",

"build:staging": "REACT_APP_ENV=staging npm run build",

"build:prod": "REACT_APP_ENV=production npm run build",

.env.staging.js:

REACT_APP_BASE_HREF=/staging

index.html:

....

<base href="" + process.env.REACT_APP_API_URL />

....

This doesn't seem to work in index.html. While similar setup works for JS files

(Probably because JS files are parsed and bundled into a single file and the bundler reads the values at that point of time)

Things tried:

index.html:

<base href=process.env.REACT_APP_API_URL />

<base href="process.env.REACT_APP_API_URL" />

<base href="%process.env.REACT_APP_API_URL%" /> (similar to PUBLIC_URL variable)

Setting basename property along with Browser Router also does not solve the problem

like image 865
Manmeet S. Oberoi Avatar asked Jul 20 '17 07:07

Manmeet S. Oberoi


1 Answers

This problem was solved. Follow these steps:

  1. In package.json Set homepage key to ""
  2. In .env.staging file Set PUBLIC_URL=/survey
  3. No need to use <base href>. Can be removed from HTML file
  4. Change links for stylesheet to

    <link rel="stylesheet" href="%PUBLIC_URL%/vendor/bootstrap/css/bootstrap.min.css">

No need to add process.env

like image 62
Manmeet S. Oberoi Avatar answered Oct 09 '22 15:10

Manmeet S. Oberoi