Search code examples
npmenvironment-variablescreate-react-apppackage.json

setting environment variables to modify package.json for create-react-app


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 ?


Solution

  • 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.