node.js 如何在 package.json 中使用环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34650527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use environment variables in package.json
提问by kaasdude
Because we don't want sensitive data in the project code, including the package.json file, using environment variables would be a logical choice in my opinion.
因为我们不希望项目代码中包含敏感数据,包括 package.json 文件,所以在我看来使用环境变量将是一个合乎逻辑的选择。
Example package.json:
示例 package.json:
"dependencies": {
"accounting": "~0.4.0",
"async": "~1.4.2",
"my-private-module":"git+https://${BB_USER}:${BB_PASS}@bitbucket.org/foo/bar.git"
Is this possible?
这可能吗?
(The question is notif this is wiseor not good, just if it's possible)
(问题不在于这是否明智或不好,只是是否可能)
Regards!
问候!
I.
一世。
回答by techguy2000
I have similar but different requirement. For me, I want to use environment variables in the scripts.
我有相似但不同的要求。对我来说,我想在脚本中使用环境变量。
Instead of using the environment variables directly in package.json, I do:
我没有直接在 package.json 中使用环境变量,而是:
"some-script": "./scripts/some-script.sh",
And in some-script.sh:
在 some-script.sh 中:
#!/bin/sh
npm run some-other-script -- --prop=$SOME_ENV_VAR
回答by Steve Bennett
No, it's not possible. You should access the repo using git+ssh, and store a private key in ~/.ssh.
不,这不可能。您应该使用 访问git+ssh存储库,并将私钥存储在~/.ssh.
Your line then looks like:
你的行看起来像:
"my-private-module":"git+ssh://[email protected]/foo/bar.git"
Which doesn't contain anything sensitive.
其中不包含任何敏感内容。
回答by hakunin
You can use environment values to inject in your package.json like this:
您可以使用环境值在您的 package.json 中注入,如下所示:
Any environment variables that start with npm_config_ will be interpreted as a configuration parameter. For example, putting npm_config_foo=bar in your environment will set the foo configuration parameter to bar. Any environment configurations that are not given a value will be given the value of true. Config values are case-insensitive, so NPM_CONFIG_FOO=bar will work the same.
任何以 npm_config_ 开头的环境变量都将被解释为配置参数。例如,将 npm_config_foo=bar 放在您的环境中会将 foo 配置参数设置为 bar。任何未赋予值的环境配置都将赋予 true 值。配置值不区分大小写,因此 NPM_CONFIG_FOO=bar 的工作方式相同。
回答by mscdex
No it isn't possible as npm does not treat any string values as any kind of templates.
不,这是不可能的,因为 npm 不会将任何字符串值视为任何类型的模板。
It may be better to just use git+ssh(if your provider supports it) with an ssh agent.
最好将git+ssh(如果您的提供商支持)与 ssh 代理一起使用。
回答by Christophe Marois
Here's how I managed to work around package.jsonto achieve the same purpose. It uses a script that reads from a custom section of package.jsonfor URL modules, interpolates environment variables in them, and installs them with npm install --no-save(the --no-savecould be omitted, depending on the usecase).
这是我设法解决package.json以实现相同目的的方法。它使用从package.jsonfor URL 模块的自定义部分读取的脚本,在其中插入环境变量,并安装它们npm install --no-save(--no-save根据用例可以省略)。
As a bonus: it tries to read the env variable from .env.json, which can be gitignore'd, and very useful for development.
作为奖励:它尝试从 中读取 env 变量.env.json,它可以被 gitignore 忽略,并且对开发非常有用。
- Create a script that will read from a custom section of
package.json
- 创建一个脚本,该脚本将从自定义部分读取
package.json
env-dependencies.js
env-dependencies.js
const execSync = require('child_process').execSync
const pkg = require('./package.json')
if (!pkg.envDependencies) {
return process.exit(0)
}
let env = Object.assign({}, process.env)
if (typeof pkg.envDependencies.localJSON === 'string') {
try {
Object.assign(env, require(pkg.envDependencies.localJSON))
} catch (err) {
console.log(`Could not read or parse pkg.envDependencies.localJSON. Processing with env only.`)
}
}
if (typeof pkg.envDependencies.urls === 'undefined') {
console.log(`pkg.envDependencies.urls not found or empty. Passing.`)
process.exit(0)
}
if (
!Array.isArray(pkg.envDependencies.urls) ||
!(pkg.envDependencies.urls.every(url => typeof url === 'string'))
) {
throw new Error(`pkg.envDependencies.urls should have a signature of String[]`)
}
const parsed = pkg.envDependencies.urls
.map(url => url.replace(/${([0-9a-zA-Z_]*)}/g, (_, varName) => {
if (typeof env[varName] === 'string') {
return env[varName]
} else {
throw new Error(`Could not read env variable ${varName} in url ${url}`)
}
}))
.join(' ')
try {
execSync('npm install --no-save ' + parsed, { stdio: [0, 1, 2] })
process.exit(0)
} catch (err) {
throw new Error('Could not install pkg.envDependencies. Are you sure the remote URLs all have a package.json?')
}
Add a
"postinstall": "node env-dependencies.js"to yourpackage.json, that way it will be run on everynpm installAdd your private git repos to
package.jsonusing the URLs you want (note: they all must have apackage.jsonat root!):
添加一个
"postinstall": "node env-dependencies.js"到您的package.json,这样它将在每个npm install添加您的私有 git 存储库以
package.json使用您想要的 URL(注意:它们都必须有一个package.json根目录!):
"envDependencies": {
"localJSON": "./.env.json",
"urls": [
"git+https://${GITHUB_PERSONAL_ACCESS_TOKEN}@github.com/user/repo#semver:^2.0.0"
]
},
(the semver specifier #semver:^2.0.0can be omitted, but refers to a git tag, which can be very useful, as it makes your git server a fully-fledge package manager)
(semver 说明符#semver:^2.0.0可以省略,但指的是 git 标记,这非常有用,因为它使您的 git 服务器成为一个成熟的包管理器)
npm install
npm install
回答by Long Nguyen
Let's use grep to get a value environment variable from the .env file.
让我们使用 grep 从 .env 文件中获取值环境变量。
"scripts": {
"start": "NODE_ENV=$(grep NODE_ENV .env | cut -d '=' -f2) some_script"
}

