Created
April 30, 2021 21:24
-
-
Save jfmoy/6ad861f907d102b1bb5dbdeec0844eee to your computer and use it in GitHub Desktop.
Private NPM dependencies with Yarn using Github token interpolation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This file is a workaround to inject the Github credentials in package.json when fetching | |
// private dependencies. This script needs to be added to "postinstall": https://yarnpkg.com/advanced/lifecycle-scripts | |
// You will need yarn-add-no-save: `yarn add yarn-add-no-save --dev` and dotenv: `yarn add dotenv --dev`. | |
// Based on a SO post that I can no longer find. | |
const execSync = require('child_process').execSync; | |
const pkg = require('./package.json'); | |
// Import the environment variables | |
require('dotenv').config(); | |
if (!pkg.envDependencies) { | |
return process.exit(0); | |
} | |
if ( | |
!Array.isArray(pkg.envDependencies) || | |
!pkg.envDependencies.every((url) => typeof url === 'string') | |
) { | |
throw new Error(`pkg.envDependencies should have a signature of String[]`); | |
} | |
const parsed = pkg.envDependencies | |
.map((url) => | |
url.replace(/\${([0-9a-zA-Z_]*)}/g, (_, varName) => { | |
if (typeof process.env[varName] === 'string') { | |
return process.env[varName]; | |
} else { | |
throw new Error( | |
`Could not read environment variable ${varName} in url ${url}`, | |
); | |
} | |
}), | |
) | |
.join(' '); | |
try { | |
execSync('yarn add-no-save --silent --ignore-scripts ' + parsed, { | |
stdio: [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?', | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment