Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created May 3, 2018 13:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JamieMason/d5f5e4251c816ad6fc51c89904dc7388 to your computer and use it in GitHub Desktop.
Save JamieMason/d5f5e4251c816ad6fc51c89904dc7388 to your computer and use it in GitHub Desktop.
Replace semver ranges with exact version numbers in package.json files
const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const filePaths = glob
.sync('package.json')
.concat(glob.sync('packages/*/package.json'))
.map(filePath => path.resolve(process.cwd(), filePath));
const reinstall = (filePath, data, key) => {
const dependencyVersions = Object.entries(data[key]).map(
([name, version]) => `${name}@${version}`
);
const options = key === 'dependencies' ? ['--save'] : ['--save', '--save-dev'];
childProcess.spawnSync('npm', ['install'].concat(options).concat(dependencyVersions), {
cwd: filePath.replace('/package.json', ''),
encoding: 'utf-8',
env: process.env,
stdio: 'pipe'
});
};
filePaths.forEach(filePath => {
console.log(filePath);
const raw = fs.readFileSync(filePath, { encoding: 'utf8' });
const clone = JSON.parse(raw);
clone.dependencies && (clone.dependencies = {});
clone.devDependencies && (clone.devDependencies = {});
fs.writeFileSync(filePath, JSON.stringify(clone, null, 2), { encoding: 'utf8' });
const data = JSON.parse(raw);
data.dependencies && reinstall(filePath, data, 'dependencies');
data.devDependencies && reinstall(filePath, data, 'devDependencies');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment