简体   繁体   English

如何在 package.json 中使用环境变量

[英]How to use environment variables in package.json

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"

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"
}

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

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://git@bitbucket.org/foo/bar.git"

Which doesn't contain anything sensitive.其中不包含任何敏感内容。

Here's how I managed to work around package.json to achieve the same purpose.这是我如何设法解决package.json以达到相同的目的。 It uses a script that reads from a custom section of package.json for URL modules, interpolates environment variables in them, and installs them with npm install --no-save (the --no-save could be omitted, depending on the usecase).它使用从package.json的自定义部分读取 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.json读取 env 变量,该变量可以被 gitignore 删除,并且对开发非常有用。

  1. Create a script that will read from a custom section of package.json创建将从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?')
}
  1. Add a "postinstall": "node env-dependencies.js" to your package.json , that way it will be run on every npm install添加一个"postinstall": "node env-dependencies.js"到你的package.json ,这样它就会在每个npm installnpm install

  2. Add your private git repos to package.json using the URLs you want (note: they all must have a package.json at root!):使用您想要的 URL 将您的私有 git 存储库添加到package.json (注意:它们都必须在根目录中有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.0 can 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 服务器成为一个成熟的包管理器)

  1. npm install

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 代理一起使用可能会更好。

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.任何以 npm_config_ 开头的环境变量都将被解释为配置参数。 For example, putting npm_config_foo=bar in your environment will set the foo configuration parameter to bar.例如,将 npm_config_foo=bar 放在您的环境中会将 foo 配置参数设置为 bar。 Any environment configurations that are not given a value will be given the value of true.任何未赋予值的环境配置都将赋予 true 值。 Config values are case-insensitive, so NPM_CONFIG_FOO=bar will work the same.配置值不区分大小写,因此 NPM_CONFIG_FOO=bar 的工作方式相同。

https://docs.npmjs.com/misc/config#environment-variables https://docs.npmjs.com/misc/config#environment-variables

Very Simple and straight solution...非常简单直接的解决方案......

  1. Create .env file at the same directory level where package.json resides.在 package.json 所在的同一目录级别创建 .env 文件。
  2. Mention PERSONAL_ACCESS_TOKEN=******************************* into .env file在 .env 文件中提及 PERSONAL_ACCESS_TOKEN=***********************************
  3. Dont forget to add '.env' into .gitingore list which will prevent exposing key to outside world while you make git commit to your repo.不要忘记将“.env”添加到 .gitingore 列表中,这将防止在您将 git 提交到您的存储库时将密钥暴露给外部世界。
  4. Now you can add your dependency in package.json as below,现在您可以在 package.json 中添加您的依赖项,如下所示,

Package.json包.json

"dependencies": { ... "my-private-github-repo": "git+https://${ENV.PERSONAL_ACCESS_TOKEN}@github.com/USER/abcd-repo-3.4.0.git", ... } "dependencies": { ... "my-private-github-repo": "git+https://${ENV.PERSONAL_ACCESS_TOKEN}@github.com/USER/abcd-repo-3.4.0.git", . .. }

There are other ways using 'DOTENV' npm package, but it could not do much when we are trying to resolve "Github" package dependency.还有其他使用“DOTENV”npm 包的方法,但是当我们尝试解决“Github”包依赖性时,它无能为力。 Above seems to be straight forward solution.以上似乎是直接的解决方案。

I had the same need and my solution was based on @Long Nguyen's response .我有同样的需求,我的解决方案基于@Long Nguyen 的回应 This way, I can only rely on what's defined on the .env file.这样,我只能依赖 .env 文件中定义的内容。

.env .env

...
SKIP_PREFLIGHT_CHECK=true
...

package.json包.json

...
"scripts": {
  "test": "yarn cross-env $(grep SKIP_PREFLIGHT_CHECK ../../.env) react-app-rewired test --watchAll=false"
}
...

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

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