简体   繁体   中英

Accessing environment variables in package.json

Recently I started working on a pretty old application where API endpoint URL differs on each system.

Right now, my package.json looks like this:

"start": "cross-env API_ENDPOINT=http://localhost:5000/api/v1 react-scripts start"

The problem is, this value is currently static so when I deploy the code into Heroku, it tries to connect my localhost. Instead, I'm looking to do something like this:

"start": "cross-env API_ENDPOINT={thisShouldBeDynamic} api/v1 react-scripts start"

Is there any way to do it?

Ps. react-app-scripts version is ^0.4.0 so I cannot rely on .env and believe me, you wouldn't want to update it.

JSON format doesn't support templating itself, so you need to create a script which will opens config.json , update it and save back to same file.

You can start from https://www.npmjs.com/package/config-template and create your own template filler which retrieve env variables you need and add them to config file, then same a file.

You can alter your installation before it starts up with the postinstall NPM hook. https://devcenter.heroku.com/articles/nodejs-support#customizing-the-build-process

For instance:

"scripts": {
   "postinstall": "node ./ops/heroku-build.js"
}

And then in that script, simply read the appropriate env variables. process.env holds all the Heroku environment variables. Use those to edit your package.json .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM