forked from vercel/next.js
/
name-default-component.ts
94 lines (75 loc) · 2.45 KB
/
name-default-component.ts
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
import { basename, extname } from 'path'
const camelCase = (value: string): string => {
const val: string = value.replace(/[-_\s.]+(.)?/g, (_match, chr) =>
chr ? chr.toUpperCase() : ''
)
return val.substr(0, 1).toUpperCase() + val.substr(1)
}
const isValidIdentifier = (value: string): boolean =>
/^[a-zA-ZÀ-ÿ][0-9a-zA-ZÀ-ÿ]+$/.test(value)
type Node = {
type: string
declaration: {
type: string
body: any
id?: any
}
}
export default function transformer(file, api, options) {
const j = api.jscodeshift
const root = j(file.source)
let hasModifications: boolean
const isJSX = (node): boolean =>
node.type === 'JSXElement' ||
(node.type === 'BlockStatement' &&
j(node)
.find(j.ReturnStatement)
.some((path) => path.value.argument?.type === 'JSXElement'))
const hasRootAsParent = (path): boolean => {
const program = path.parentPath.parentPath.parentPath.parentPath.parentPath
return !program || program?.value?.type === 'Program'
}
const nameFunctionComponent = (path): void => {
const node: Node = path.value
if (!node.declaration) {
return
}
const isArrowFunction =
node.declaration.type === 'ArrowFunctionExpression' &&
isJSX(node.declaration.body)
const isAnonymousFunction =
node.declaration.type === 'FunctionDeclaration' && !node.declaration.id
if (!(isArrowFunction || isAnonymousFunction)) {
return
}
const fileName: string = basename(file.path, extname(file.path))
let name: string = camelCase(fileName)
// If the generated name looks off, don't add a name
if (!isValidIdentifier(name)) {
return
}
// Add `Component` to the end of the name if an identifier with the
// same name already exists
while (root.find(j.Identifier, { name }).some(hasRootAsParent)) {
// If the name is still duplicated then don't add a name
if (name.endsWith('Component')) {
return
}
name += 'Component'
}
hasModifications = true
if (isArrowFunction) {
path.insertBefore(
j.variableDeclaration('const', [
j.variableDeclarator(j.identifier(name), node.declaration),
])
)
node.declaration = j.identifier(name)
} else {
// Anonymous Function
node.declaration.id = j.identifier(name)
}
}
root.find(j.ExportDefaultDeclaration).forEach(nameFunctionComponent)
return hasModifications ? root.toSource(options) : null
}