-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
104 lines (87 loc) · 2.92 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import fs from 'fs';
import path from 'path';
import config from './vite.config.js';
const { resolve } = config;
const projectDirectory = './src'; // Replace with your project's directory
// Function to recursively find JavaScript and Vue files
function findFiles(dir, filePattern) {
let files = [];
fs.readdirSync(dir).forEach((file) => {
const filePath = path.join(dir, file);
const fileStat = fs.statSync(filePath);
if (fileStat.isDirectory()) {
files = files.concat(findFiles(filePath, filePattern));
} else if (filePattern.test(file)) {
files.push(filePath);
}
});
return files;
}
// Function to add file extension to module imports
function addFileExtensions(files) {
files.forEach((file) => {
fs.readFile(file, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file: ${file}`);
console.error(err);
return;
}
const updatedData = data.replaceAll(
// this regex matches on import('path/to/foo') and import foo from 'path/to/foo'
/(import\s+{?[^}]*?}?\s+from\s+['"])([^.'"]+)(['"]\s*;)|(import\s*\([\s\S]*?['"])([^'"]+[^/])(['"]\s*[\s\S]*?\)\s*)/g,
(match, p1, p2, p3, p4, p5, p6) => {
//depending on which regex pattern is matched, it will populate groups 1-3 or 4-6
const g1 = p1 || p4;
const g2 = p2 || p5;
const g3 = p3 || p6;
let filePath = path.join(path.dirname(file), g2);
if (!g2.startsWith('.')) {
filePath = resolveAlias(g2);
}
const jsFile = fs.existsSync(`${filePath}.js`);
const vueFile = fs.existsSync(`${filePath}.vue`);
const ifIndexExists = fs.existsSync(`${filePath}/index.js`);
if (jsFile) {
return `${g1}${g2}.js${g3}`;
}
if (vueFile) {
return `${g1}${g2}.vue${g3}`;
}
if (ifIndexExists) {
return `${g1}${g2}${g3}`;
}
return match;
},
);
if (data !== updatedData) {
fs.writeFile(file, updatedData, 'utf8', (writeErr) => {
if (writeErr) {
console.error(`Error writing file: ${file}`);
console.error(writeErr);
} else {
console.log(`File updated: ${file}`);
}
});
}
});
});
}
// Function to resolve aliases from vite.config.js
function resolveAlias(filePath) {
const viteConfigPath = path.join('vite.config.js');
if (fs.existsSync(viteConfigPath)) {
if (resolve && resolve.alias) {
for (const alias in resolve.alias) {
if (filePath.startsWith(alias)) {
const resolvedPath = filePath.replace(alias, resolve.alias[alias]);
return resolvedPath;
}
}
}
}
return filePath;
}
// Entry point
const filePattern = /\.(js|vue)$/i;
const files = findFiles(projectDirectory, filePattern);
addFileExtensions(files);