Skip to content

Instantly share code, notes, and snippets.

@viters
Last active December 10, 2019 19:19
Show Gist options
  • Save viters/e31bbe6c842f178e6955cae1211e8953 to your computer and use it in GitHub Desktop.
Save viters/e31bbe6c842f178e6955cae1211e8953 to your computer and use it in GitHub Desktop.
Read package version from yarn.lock

read-yarn-lock

Example:

> npx -q https://gist.github.com/viters/e31bbe6c842f178e6955cae1211e8953 yarn.lock prettier
[email protected]

May be used in scripts such as:

yarn global add $(npx -q https://gist.github.com/viters/e31bbe6c842f178e6955cae1211e8953 yarn.lock prettier)

I use it in CI environment in some jobs to install only portion of dependencies to quicken pipeline.

#!/usr/bin/env node
const fs = require('fs');
const lockfile = require('@yarnpkg/lockfile');
if (!process.argv[2]) {
throw Error('Provide path to yarn.lock file');
}
if (!process.argv[3]) {
throw Error('Provide package name');
}
const file = fs.readFileSync(process.argv[2], 'utf8');
const json = lockfile.parse(file);
const key = Object.keys(json.object).find(a => a.split('@')[0] === process.argv[3]);
if (!key) {
throw Error(process.argv[3] + ' package not found');
}
console.log(process.argv[3] + '@' + json.object[key].version);
{
"name": "read-yarn-lock",
"version": "1.0.0",
"description": "Parse yarn.lock and get currently used pkg version",
"main": "index.js",
"bin": "index.js",
"author": "[email protected]",
"license": "MIT",
"dependencies": {
"@yarnpkg/lockfile": "^1.1.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment