Use enviroment variables in yarn package.json

﹥>﹥吖頭↗ 提交于 2019-12-05 19:47:52

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!