-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathgeneratePackages.cjs
75 lines (68 loc) · 2.04 KB
/
generatePackages.cjs
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
65
66
67
68
69
70
71
72
73
74
75
const path = require('path');
const fsPromises = require('fs/promises');
const packageJson = require('./package.json');
console.log(`\ngeneratePackages start`);
const distDir = 'dist';
const mainDir = 'src/lib';
const packageExports = packageJson.exports;
const packageFiles = packageJson.files;
const generatePackage = async (fileName) => {
const [baseName] = fileName.split('.');
const dirName = baseName;
const typeFileName = `${baseName}.d.ts`;
// populate exports path
packageExports[`./${baseName}`] = {
types: `./${path.join(distDir, 'esm', 'lib', typeFileName)}`,
import: `./${path.join(distDir, 'esm', 'lib', fileName)}`,
browser: `./${path.join(distDir, 'esm', 'lib', fileName)}`,
default: `./${path.join(distDir, 'esm', 'lib', fileName)}`,
};
// create fallback package for unsupported exports map cases
await fsPromises
.rm(dirName, { recursive: true, force: true })
.catch(() => {});
await fsPromises.mkdir(dirName, { recursive: true });
await fsPromises.writeFile(
path.join(dirName, 'package.json'),
JSON.stringify(
{
type: 'module',
types: `../${path.join(distDir, 'esm', 'lib', typeFileName)}`,
main: `../${path.join(distDir, 'esm', 'lib', fileName)}`,
},
null,
2,
).concat('\n'),
);
if (!packageFiles.includes(dirName)) {
packageFiles.push(dirName);
}
};
fsPromises
.readdir(mainDir)
.then((fileNames) =>
Promise.all(
fileNames
.filter(
(name) =>
name.split('.').length === 2 &&
name.endsWith('.js') &&
name !== 'index.js',
)
.map(generatePackage),
).then((res) => {
console.log(`${res.length} packages generated`);
}),
)
.then(() => {
console.log('updating package.json');
packageJson.exports = packageExports;
packageJson.files = packageFiles;
return fsPromises.writeFile(
'package.json',
JSON.stringify(packageJson, null, 2).concat('\n'),
);
})
.then(() => {
console.log('generatePackages done');
});