Created
November 26, 2019 07:11
-
-
Save caaatisgood/1961ca72d1850487698e944b227434d0 to your computer and use it in GitHub Desktop.
save exact dependencies in package.json based on your yarn.lock
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
const PATH_TO_PACKAGE_JSON = './package.json' | |
const PATH_TO_YARN_LOCK = './yarn.lock' | |
const fs = require('fs') | |
const _log = ({ type, value }) => { | |
console.log(`[ inYarnWeLock ${type} ]` + (value ? ` - ${value}` : '')) | |
} | |
const _getSchemedDep = ({ name, version }) => `${name}@${version}` | |
const _getDepsFromPackage = ({ dependencies, devDependencies }) => { | |
const allDeps = { ...dependencies, ...devDependencies } | |
return Object.entries(allDeps).map(([name, version]) => ({ | |
name, | |
version | |
})) | |
} | |
const _readFile = (filePath) => { | |
try { | |
return fs.readFileSync(filePath) | |
} catch (err) { | |
_log({ type: 'failed to read', value: `[ ${filePath} ] - ${err}` }) | |
} | |
} | |
const _getLockedDepsFromLockFile = (deps) => { | |
const lockFile = _readFile(PATH_TO_YARN_LOCK) | |
return deps.map(({ name, version }) => { | |
const schemedDep = _getSchemedDep({ name, version }) | |
const lockIndex = lockFile.indexOf(schemedDep) | |
const [, exactVersion] = lockFile | |
.slice(lockIndex) | |
.toString() | |
.match(/version "(.*)"/) | |
return { | |
name, | |
exactVersion | |
} | |
}) | |
} | |
const _writePackageDependencies = (deps) => { | |
let pkg = _readFile(PATH_TO_PACKAGE_JSON).toString() | |
deps.forEach(({ name, exactVersion }) => { | |
pkg = pkg.replace(new RegExp(`"${name}": ".*"`), `"${name}": "${exactVersion}"`) | |
}) | |
try { | |
fs.writeFileSync(PATH_TO_PACKAGE_JSON, pkg) | |
} catch (err) { | |
_log({ type: 'failed to write', value: err }) | |
} | |
} | |
const inYarnWeLock = () => { | |
_log({ type: 'starts' }) | |
_log({ type: `get dependencies from ${PATH_TO_PACKAGE_JSON}` }) | |
const pkg = require(PATH_TO_PACKAGE_JSON) | |
const deps = _getDepsFromPackage(pkg) | |
_log({ type: `get exact dependencies from ${PATH_TO_YARN_LOCK}` }) | |
const lockedDeps = _getLockedDepsFromLockFile(deps) | |
_log({ type: `write exact dependencies to ${PATH_TO_PACKAGE_JSON}` }) | |
_writePackageDependencies(lockedDeps) | |
_log({ type: 'done' }) | |
} | |
inYarnWeLock() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment