-
Notifications
You must be signed in to change notification settings - Fork 13
/
sync-package-versions.mjs
44 lines (33 loc) · 1.38 KB
/
sync-package-versions.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import fs from 'node:fs';
const rootPackage = JSON.parse(fs.readFileSync('./package.json'));
const subPackages = rootPackage.workspaces
.map((packagePath) => {
const contents = fs.readFileSync(`./${packagePath}/package.json`);
return {
path: packagePath,
package: JSON.parse(contents),
contents: String(contents),
};
});
const { packages = [] } = rootPackage['sync-package-versions'] ?? {};
const updatedSubPackages = subPackages.map((subPackage) => {
let contents = subPackage.contents;
contents = packages.reduce((contents, packageName) => {
const packageVersion = rootPackage.dependencies?.[packageName]
?? rootPackage.peerDependencies?.[packageName]
?? rootPackage.devDependencies?.[packageName];
if (!packageVersion) return contents;
return contents.replace(
new RegExp(`"${packageName}":\\s+"([^"]+)"`, 'g'),
(matchedString, matchedVersion) => matchedString.replace(matchedVersion, packageVersion),
);
}, contents);
if (contents === subPackage.contents) {
return undefined;
}
return { ...subPackage, contents }
}).filter(Boolean);
updatedSubPackages.forEach((subPackage) => {
console.log(`Writing ${subPackage.path}/package.json`);
fs.writeFileSync(`${subPackage.path}/package.json`, subPackage.contents);
})