-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathfix-esm-imports.js
More file actions
77 lines (64 loc) · 2.05 KB
/
fix-esm-imports.js
File metadata and controls
77 lines (64 loc) · 2.05 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
const fs = require('fs');
const path = require('path');
function fixImportsInFile(filePath) {
let content = fs.readFileSync(filePath, 'utf8');
let modified = false;
// Fix relative imports that don't end with .js
content = content.replace(
/from\s+['"](\.[^'"]*?)(?<!\.js)(['"])/g,
(match, importPath, quote) => {
// Skip if it already ends with .js
if (importPath.endsWith('.js')) {
return match;
}
modified = true;
console.log(`Fixed import in ${filePath}: ${importPath} -> ${importPath}.js`);
return `from ${quote}${importPath}.js${quote}`;
}
);
// Fix import statements that don't end with .js
content = content.replace(
/import\s+([^'"]*?)\s+from\s+['"](\.[^'"]*?)(?<!\.js)(['"])/g,
(match, importedItems, importPath, quote) => {
if (importPath.endsWith('.js')) {
return match;
}
modified = true;
console.log(`Fixed import in ${filePath}: ${importPath} -> ${importPath}.js`);
return `import ${importedItems} from ${quote}${importPath}.js${quote}`;
}
);
if (modified) {
fs.writeFileSync(filePath, content);
console.log(`✅ Fixed imports in: ${filePath}`);
}
return modified;
}
function fixImportsInDirectory(dir) {
const files = fs.readdirSync(dir, { withFileTypes: true });
let totalFixed = 0;
for (const file of files) {
const fullPath = path.join(dir, file.name);
if (file.isDirectory()) {
totalFixed += fixImportsInDirectory(fullPath);
} else if (file.name.endsWith('.js')) {
if (fixImportsInFile(fullPath)) {
totalFixed++;
}
}
}
return totalFixed;
}
console.log('🔧 Fixing ESM imports...');
const esmDir = './dist/esm';
if (!fs.existsSync(esmDir)) {
console.error('❌ ESM directory not found:', esmDir);
process.exit(1);
}
const fixedCount = fixImportsInDirectory(esmDir);
console.log(`\n✅ Fixed imports in ${fixedCount} files`);
if (fixedCount > 0) {
console.log('\n🎉 All ESM imports have been fixed!');
} else {
console.log('\n✨ No imports needed fixing.');
}