Use enviroment variables in yarn package.json

2019-05-10 18:39发布

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.

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

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?

1条回答
趁早两清
2楼-- · 2019-05-10 19:20

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 example:

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));

Bonus:

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

查看更多
登录 后发表回答