kaa*_*ude 29 heroku node.js npm
因为我们不希望项目代码中包含敏感数据,包括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"
Run Code Online (Sandbox Code Playgroud)
这可能吗?
(问题不在于这是否明智或不好,只要它是可能的)
问候!
一世.
Lon*_*yen 27
让我们使用 grep 从 .env 文件中获取值环境变量。
"scripts": {
"start": "NODE_ENV=$(grep NODE_ENV .env | cut -d '=' -f2) some_script"
}
Run Code Online (Sandbox Code Playgroud)
不,这不可能。您应该使用 访问git+ssh
存储库,并将私钥存储在~/.ssh
.
你的行看起来像:
"my-private-module":"git+ssh://git@bitbucket.org/foo/bar.git"
Run Code Online (Sandbox Code Playgroud)
其中不包含任何敏感内容。
这是我设法解决package.json
以实现相同目的的方法。它使用从package.json
for URL 模块的自定义部分读取的脚本,在其中插入环境变量,并安装它们npm install --no-save
(--no-save
根据用例可以省略)。
作为奖励:它尝试从 中读取 env 变量.env.json
,它可以被 gitignore 忽略,并且对开发非常有用。
package.json
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?')
}
Run Code Online (Sandbox Code Playgroud)
添加一个"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"
]
},
Run Code Online (Sandbox Code Playgroud)
(semver 说明符#semver:^2.0.0
可以省略,但指的是 git 标记,这非常有用,因为它使您的 git 服务器成为一个成熟的包管理器)
npm install
我有类似但不同的要求。对我来说,我想在脚本中使用环境变量。
我不是直接在package.json中使用环境变量,而是:
"some-script": "./scripts/some-script.sh",
Run Code Online (Sandbox Code Playgroud)
在some-script.sh中:
#!/bin/sh
npm run some-other-script -- --prop=$SOME_ENV_VAR
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16023 次 |
最近记录: |