-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbuild-esm.js
More file actions
84 lines (72 loc) · 2.52 KB
/
build-esm.js
File metadata and controls
84 lines (72 loc) · 2.52 KB
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
76
77
78
79
80
81
82
83
84
const esbuild = require('esbuild');
const { esbuildPluginFilePathExtensions } = require('esbuild-plugin-file-path-extensions');
const fs = require('fs');
async function buildESM() {
try {
// Clean and create dist-esm directory
if (fs.existsSync('./dist-esm')) {
fs.rmSync('./dist-esm', { recursive: true, force: true });
}
fs.mkdirSync('./dist-esm', { recursive: true });
// Get all TypeScript files
const glob = require('glob');
const entryPoints = glob.sync('./src/**/*.ts');
// Build ESM with file path extensions
await esbuild.build({
entryPoints,
bundle: false, // Don't bundle - keep separate files
outdir: './dist-esm',
format: 'esm',
target: 'es2021',
platform: 'neutral',
sourcemap: false,
outExtension: { '.js': '.mjs' },
plugins: [esbuildPluginFilePathExtensions({
esmExtension: '.mjs',
filter: /\.ts$/
})],
});
// Create package.json for ESM
fs.writeFileSync('./dist-esm/package.json', '{"type":"module"}\n');
// Post-process to fix import extensions
const fixImportExtensions = (dir) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = `${dir}/${file}`;
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
fixImportExtensions(filePath);
} else if (file.endsWith('.mjs')) {
let content = fs.readFileSync(filePath, 'utf8');
// Fix relative imports that don't have .mjs extension
content = content.replace(
/from\s+["'](\.[^"']+)["']/g,
(match, importPath) => {
if (!importPath.endsWith('.mjs') && !importPath.endsWith('.js')) {
return match.replace(importPath, importPath + '.mjs');
}
return match;
}
);
// Fix import statements too
content = content.replace(
/import\s+[^"']*from\s+["'](\.[^"']+)["']/g,
(match, importPath) => {
if (!importPath.endsWith('.mjs') && !importPath.endsWith('.js')) {
return match.replace(importPath, importPath + '.mjs');
}
return match;
}
);
fs.writeFileSync(filePath, content);
}
}
};
fixImportExtensions('./dist-esm');
console.log('✅ ESM build completed with file extensions');
} catch (error) {
console.error('❌ ESM build failed:', error);
process.exit(1);
}
}
buildESM();