是否可以在npm/package.json内部使用环境变量? [英] Is it possible to consume environment variables inside of npm / package.json?

查看:236
本文介绍了是否可以在npm/package.json内部使用环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建package.json,以便在Heroku上运行NodeJS应用程序时,它将使用环境变量运行scripts.postinstall步骤.例如:

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"™?

推荐答案

回答最后一个问题,因为它们是最重要的一个:是,否,绝对是,因为您刚刚破坏了跨平台的兼容性.无法保证您的环境语法适用于所有操作系统上的所有shell,因此请不要这样做.

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.

我们已经为我们提供了有保证的跨平台技术:节点.因此,创建一个名为bootstrap.js之类的文件,然后使npm运行node bootstrap作为您的安装后脚本.由于bootstrap.js中的代码将像其他任何节点脚本一样运行,因此它可以完全跨平台兼容的方式访问process.env,每个人都会很高兴.

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.

许多使用通用utils的许多东西都有节点等效项,因此您可以npm在本地而不是全局安装它们,然后在npm脚本中调用它们.例如,mkdir -p不是跨平台的,但是安装mkdirp模块是,然后像"ensuredirs": "mkdirp dist/assets"这样的npm脚本在以npm run ensuredirs

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

为了方便起见,最常见的unix实用程序具有自己的运行程序包 shx ,完全跨平台,使开发人员的生活更加轻松.

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.

这篇关于是否可以在npm/package.json内部使用环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆