2

I discovered today the use of environment variables in React, and I love it ! Especially using react-router, and filling up the basename attribute of the <BrowserRouter> component this way :

<BrowserRouter basename={`${process.env.REACT_APP_BASENAME}`}>
</BrowserRouter>

It's great, but I would like to use the variable REACT_APP_BASENAME also in package.json file, because as you know, the "homepage" line in package.json define the PUBLIC_URL variable used in index.html as %PUBLIC_URL%, and I would like this PUBLIC_URL to be equal to my REACT_APP_BASENAME variable. I think I would need something like that :

package.json :

{
  "name": "apoc",
  "version": "0.1.0",
  "private": true,
  "homepage": "%REACT_APP_BASENAME%",
  "dependencies": {....

Is it possible ?

2 Answers 2

2

By going through some files in node-modules/react-scripts/config, I discovered in the webpack.config files that PUBLIC_URL is provided to the app as %PUBLIC_URL% in HTML files and process.env.PUBLIC_URL in JavaScript.

As the target was to be able to use the same variable also in JavaScript, there is actually no need to repeat the same path in any .env file : just set once the path in package.json at "homepage" line and you're good to use PUBLIC_URL wherever you want, HTML or JS.

Sign up to request clarification or add additional context in comments.

Comments

-1

You can use an environment variable in your package.json like this.

Cross platform

{
  "name": "apoc",
  "version": "0.1.0",
  "private": true,
  "homepage": "cross-var echo ${REACT_APP_BASENAME}",
  "dependencies": {....

12 Comments

Seems to work, although my terminal is telling me The project was built assuming it is hosted at cross-var%20echo%20$%7BREACT_APP_BASENAME%7D/. What do you think ?
Are you on windows?
Actually, something I didn't get is that the homepage parameter in the package.json is the parameter modifying the %PUBLIC_URL% in index.html, is that right ? Meaning that if I there is no %PUBLIC_URL% in index.html anymore, the homepage parameter is useless, isn't it ?
On unix systems you can just use "homepage": "echo ${REACT_APP_BASENAME}",
The point is that if index.html is in a subdirectory and if I need the subdirectory path in index.html and in other files (such as some React components), the homepage parameter alone is not working because it's only replacing %PUBLIC_URL% in index.html, therefore I need to implement env variables for the other files. Then comes the question : in order to keep along with the DRY principle, how do you change the homepage parameter with an env variable defined in a .env.production file ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.