Use enviroment variables in yarn package.json Use enviroment variables in yarn package.json heroku heroku

Use enviroment variables in yarn package.json


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.