简体   繁体   English

访问package.json中的环境变量

[英]Accessing environment variables in package.json

Recently I started working on a pretty old application where API endpoint URL differs on each system. 最近,我开始在一个非常老的应用程序上工作,该应用程序的API端点URL在每个系统上都不同。

Right now, my package.json looks like this: 现在,我的package.json看起来像这样:

"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. 问题是,该值当前是静态的,因此当我将代码部署到Heroku中时,它将尝试连接我的本地主机。 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. react-app-scripts版本是^ 0.4.0,所以我不能依赖.env相信我,您不想更新它。

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. JSON格式不支持模板本身,因此您需要创建一个脚本,该脚本将打开config.json ,对其进行更新并保存回同一文件。

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. 您可以从https://www.npmjs.com/package/config-template开始,并创建自己的模板填充器,该填充器检索所需的env变量并将它们添加到配置文件中,然后再添加一个文件。

You can alter your installation before it starts up with the postinstall NPM hook. 您可以使用postinstall NPM挂钩在启动之前更改安装。 https://devcenter.heroku.com/articles/nodejs-support#customizing-the-build-process 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. 然后在该脚本中,只需读取相应的env变量即可。 process.env holds all the Heroku environment variables. process.env包含所有Heroku环境变量。 Use those to edit your package.json . 使用这些来编辑package.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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