Is it possible to consume environment variables inside of npm / package.json?

爷,独闯天下 提交于 2020-01-14 07:39:09

问题


I'm attempting to build a package.json so that when running a NodeJS app on Heroku it will run the scripts.postinstall step using an environment variable. For example:

...
"scripts": {
  "postinstall": "command $ENV_VAR"}
},
...

I've looked at the docs and wasn't able to find something saying I can.

Is this even possible? Is this even desirable and "I'm Doing It Wrong"™?


回答1:


To answer the last questions, because they're the most important one: yes, no, and absolutely, because you've just broken cross-platform compatibility. There is no guarantee your environment syntax works for all shells on all operating systems, so don't do this.

We have a guaranteed cross-platform technology available to us already: Node. So, create a file called something like bootstrap.js, and then make npm run node bootstrap as your postinstall script. Since the code inside bootstrap.js will run like any other node script, it'll have access to process.env in a fully cross-platform compatible way, and everyone will be happy.

And many, many, many things that use common utils have node equivalents, so you can npm install them, locally rather than globally, and then call them in an npm script. For instance mkdir -p is not cross-platform, but installing the mkdirp module is, and then an npm script like "ensuredirs": "mkdirp dist/assets" works fine everywhere when run as npm run ensuredirs

And for convenience, the most common unix utilities have their own runner package, shx, which is fully cross-platform and makes the lives of devs even easier.




回答2:


Ignore the nay-sayers. You can do this in a cross-platform manner using cross-var:

"scripts": {
    "postinstall": "cross-var command $ENV_VAR"
}


来源:https://stackoverflow.com/questions/32980057/is-it-possible-to-consume-environment-variables-inside-of-npm-package-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!