-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd-import-extension.js
44 lines (33 loc) · 1.05 KB
/
add-import-extension.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
#!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync } from 'fs'
import globby from 'globby'
import { dirname, join } from 'path'
const [, , targetDir] = process.argv
if (!targetDir) {
throw new Error('Specify target directory')
}
const files = await globby(`${targetDir}/**/*.{ts,tsx}`)
files.forEach((filepath) => {
console.log(filepath)
const content = readFileSync(filepath, 'utf8')
const replaced = content.replace(
/((?:^|\s|;)(?:import|export)\s[^'"]*['"])(\.{1,2}(?:\/[^'"]+)?)(['"](?:$|\s|;))/gm,
(_, m1, importPath, m3) => {
const resolvedPath = join(dirname(filepath), importPath)
if (
existsSync(`${resolvedPath}.ts`) ||
existsSync(`${resolvedPath}.tsx`)
) {
return `${m1}${importPath}.js${m3}`
}
if (
existsSync(join(resolvedPath, 'index.ts')) ||
existsSync(join(resolvedPath, 'index.tsx'))
) {
return `${m1}${importPath}/index.js${m3}`
}
return `${m1}${importPath}${m3}`
},
)
writeFileSync(filepath, replaced)
})