forked from module-federation/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-exports.js
61 lines (50 loc) · 1.87 KB
/
generate-exports.js
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
const fs = require('fs');
const path = require('path');
// Set the root directory
const rootDir = './packages';
// Function to update "exports" in package.json
const updateExports = (packageDir) => {
const srcDir = path.join(packageDir, 'src');
// Check if "src" directory exists
if (!fs.existsSync(srcDir)) {
console.log(`No "src" directory found in ${packageDir}. Skipping...`);
return;
}
// Read the package.json
const packageJsonPath = path.join(packageDir, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath));
// Generate "exports" field
const exportsField = {
'.': './src/index.js',
'./package.json': './package.json',
};
// Go through the src directory recursively and create mappings
const createMappings = (dir, prefix = '.') => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
entries.forEach((entry) => {
const fullPath = path.join(dir, entry.name);
const key = path.join(prefix, entry.name);
if (entry.isDirectory()) {
createMappings(fullPath, key);
} else if (entry.isFile() && path.basename(fullPath)) {
const keyWithoutExtension = key.substring(0, key.lastIndexOf('.'));
exportsField[
`./${keyWithoutExtension}`
] = `./src/${keyWithoutExtension}/index.js`;
}
});
};
createMappings(srcDir);
// Update the package.json
packageJson.exports = exportsField;
console.log(packageJson.name, packageJson.exports);
// fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
};
// Get the list of packages
const packages = fs
.readdirSync(rootDir, { withFileTypes: true })
.filter((dirent) => dirent.isDirectory())
.map((dirent) => path.join(rootDir, dirent.name));
// Update each package
packages.forEach(updateExports);
console.log('Exports field successfully updated for all packages.');