在yarn package.json中使用环境变量 [英] Use enviroment variables in yarn package.json

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

问题描述

我想从托管在bitbucket上的私有软件包中提取.由于SSH不是我的部署设置的选项,因此我想使用应用程序密码"访问存储库.

I want to pull from a private package hosted on bitbucket. Since SSH is not an option for my deploy setup, I want to access the repo using the Application Password.

所以我在JSON包中的输入如下所示:

So my entry in the package JSON looks like this:

"dependencies": {
    "@companyName/repository": "git+https://${$BITBUCKET_USER}:${BITBUCKET_APP_PASSWORD}@bitbucket.org/company name/repository.git",

将用户名和密码硬编码到存储库URL中可以很好地工作,但是当我如上所述执行yarn install时,环境变量不会被其值替换.

Coding username and password hard into the repo URL works fine but when I perform yarn install as above, the environment variables are not replaced by its values.

有没有办法使用这样的环境变量?

Is there any way to use environment variables like this?

推荐答案

您可以编写一个preinstall挂钩,用环境中的值更新package.json.幸运的是,生命周期挂钩的顺序按yarn的规定工作.

You can write a preinstall hook that updates package.json with values from the environment. Luckily the order of lifecycle hooks work as prescribed using yarn.

{
  "name": "njs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "preinstall": "node preinstall.js"
  },
  "dependencies": {
      "@companyName/repository": "git+https://${$BITBUCKET_USER}:${BITBUCKET_APP_PASSWORD}@bitbucket.org/companyName/repository.git"
  },
  "author": "",
  "license": "ISC"
}

preinstall.js 示例:

const package = require('./package.json');
const fs = require('fs');

const {BITBUCKET_USER = 'test', BITBUCKET_APP_PASSWORD='test'} = process.env;

package.dependencies["@companyName/repository"] = package.dependencies["@companyName/repository"]
    .replace("${$BITBUCKET_USER}", BITBUCKET_USER)
    .replace("${BITBUCKET_APP_PASSWORD}", BITBUCKET_APP_PASSWORD);

fs.writeFileSync('package.json', JSON.stringify(package, null, 4));

奖金:

如何选择替换preinstall.js中的环境变量由您自己决定.是的,您可以完全使用ES6模板标签.

How you choose to replace environment variables in preinstall.js is left to your good judgment. Yes, you can totally use ES6 template tags.

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

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