0

I would like to load a non standard variable from my package.json into my React frontend. For the standard package.json variables this is easily done by adding a reference to them in a .env file and then loading it in the frontend through process.env:

.env:

REACT_APP_VERSION=$npm_package_version
REACT_APP_VERSION=$npm_package_name

React frontend:

console.log(process.env.REACT_APP_VERSION)

However, when I try this with a custom variable like so:

.env:

REACT_APP_MY_VARIABLE=$npm_package_myVariable

React frontend:

console.log(process.env.REACT_APP_MY_VARIABLE)

the variable is set to an empty string in process.env


I could import package.json directly but there are some security risks that come with that

Is there a safe way to import a custom variable into a React app from package.json or do I need to find another solution?

JackHipson300
  • 75
  • 1
  • 9

1 Answers1

1

For create-react-app adding variable in package.json like this:

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "myVariable": "Hello World"
}

and .env like this REACT_APP_MY_VARIABLE=$npm_package_myVariable should work without problems but check these things:

  1. myVariable is in top level of package.json if you want to reference it by $npm_package_myVariable
  2. You are rebuilding react when you change your .env
  • I'm using the Ionic framework on top of React, maybe that it is interfering somehow? If I manually set the variable value in .env, it loads properly. It only loads as an empty string if I use the $npm_package prefix. I tried loading another standard package.json attribute and that didn't load either so it must not be pulling from package.json properly for some reason even though the version and package name that I had in the .env before load fine. Do you know of any commands I could use to try to rebuild the environment? I tried `ionic cap sync` which rebuilds the app but that didn't solve it. – JackHipson300 Feb 17 '23 at 23:19