-
Notifications
You must be signed in to change notification settings - Fork 25
/
post-build.mjs
70 lines (58 loc) · 2.51 KB
/
post-build.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
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
// In some cases, where you have { type: module } in package.json at the root
// We will workaround builds manually, since we aren't using any bundler
// tsc is missing extensions with esm exports
// and tsc doesn't export .cjs hence, index.js won't be read as cjs in cjs distribution
// See https://github.com/microsoft/TypeScript/issues/54593
import { promises as fs } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const CJS_DIR = join(__dirname, 'dist', 'cjs');
const ESM_DIR = join(__dirname, 'dist', 'esm');
async function createPackageJson(dir, type) {
const content = JSON.stringify({ type }, null, 2);
await fs.writeFile(join(dir, 'package.json'), content);
console.log(`Created package.json in ${dir}`);
}
async function renameIndexFile() {
const oldPath = join(CJS_DIR, 'index.js');
const newPath = join(CJS_DIR, 'index.cjs');
await fs.rename(oldPath, newPath);
console.log('Renamed CJS index file to index.cjs');
}
async function processEsmFiles(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory()) {
await processEsmFiles(fullPath);
} else if (entry.isFile() && entry.name.endsWith('.js')) {
let content = await fs.readFile(fullPath, 'utf8');
// Replace relative imports and exports with .js extension
// import or export, followed by optional whitespace, optional from, then optional whitespace
// skip .js if already present
const regex = /(import|export)(\s+[\s\S]*?\s+(?:from)?\s+['"])(\.\/[^'"]+)(['"])/g;
content = content.replace(regex, (match, keyword, beforePath, path, quote) => {
return `${keyword}${beforePath}${path}${path.endsWith('.js') ? '' : '.js'}${quote}`;
});
await fs.writeFile(fullPath, content);
console.log(`Processed ESM file: ${fullPath}`);
}
}
}
async function postbuild() {
try {
// Create package.json files
await createPackageJson(CJS_DIR, 'commonjs');
await createPackageJson(ESM_DIR, 'module');
// Rename index.js to index.cjs in CJS directory
await renameIndexFile();
// Process ESM files to add .js extensions
await processEsmFiles(ESM_DIR);
console.log('Postbuild completed successfully!');
} catch (error) {
console.error('Postbuild failed:', error);
process.exit(1);
}
}
postbuild();