forked from cloudinary/js-url-gen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdatePackageJsonExports.ts
64 lines (58 loc) · 1.91 KB
/
updatePackageJsonExports.ts
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* This script Adds "exports" property to package.json.
* It fills it with key-value pars for sub-directories of /dist,
* excluding /internal
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {resolve} = require('path');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {writeFile, readdirSync} = require('fs');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJson = require('../package.json');
interface Dirent {
isDirectory: () => boolean;
name: string;
}
// List of sub-directories under ./dist
const distSubDirectoriesArray: string[] = readdirSync(resolve('./dist'), {withFileTypes: true})
// Filter out files
.filter((dirent: Dirent) => dirent.isDirectory())
// Get directory name
.map((dirent: Dirent) => `./${dirent.name}`)
// Exclude /internal
.filter((dir: string) => !dir.toLowerCase().includes('/internal'))
// Sort alphabetically
.sort();
// Convert directory string to object of {[./directory/*]: { require: "directory/*.mjs", import: "directory/*.js" }}
const distSubDirectoriesObj: Record<
string,
Record<string, string>
> = distSubDirectoriesArray.reduce(
(obj, dir) => ({
...obj,
...{ [`${dir}/*`]: { require: `${dir}/*.cjs`, import: `${dir}/*.js` } },
}),
{}
);
// Generate updated package json object
const resultPackageJson = JSON.stringify({
...packageJson,
exports: {
"./bundles/umd/package.json": "./bundles/umd/package.json",
"./package.json": "./package.json",
...distSubDirectoriesObj,
".": {
"node": "./index.js",
"require": "./bundles/umd/base.js",
"default": "./index.js"
}
}
}, null, 2);
// Update (overwrite) package.json
writeFile(resolve('./package.json'), resultPackageJson, (err: Error) => {
if (!err) {
console.log('Successfully updated package.json exports field');
} else {
throw `Failed to updated package.json exports field: ${err}`;
}
});