forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
add-missing-react-import.ts
77 lines (67 loc) · 1.94 KB
/
add-missing-react-import.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
function addReactImport(j, root) {
// We create an import specifier, this is the value of an import, eg:
// import {withRouter} from 'next/router
// The specifier would be `withRouter`
const ReactDefaultSpecifier = j.importDefaultSpecifier(j.identifier('React'))
// Check if this file is already importing `react`
// so that we can attach `React` to the existing import instead of creating a new `import` node
const originalReactImport = root.find(j.ImportDeclaration, {
source: {
value: 'react',
},
})
if (originalReactImport.length > 0) {
// Check if `React` is already imported. In that case we don't have to do anything
if (originalReactImport.find(j.ImportDefaultSpecifier).length > 0) {
return
}
// Attach `React` to the existing `react` import node
originalReactImport.forEach((node) => {
node.value.specifiers.unshift(ReactDefaultSpecifier)
})
return
}
// Create import node
// import React from 'react'
const ReactImport = j.importDeclaration(
[ReactDefaultSpecifier],
j.stringLiteral('react')
)
// Find the Program, this is the top level AST node
const Program = root.find(j.Program)
// Attach the import at the top of the body
Program.forEach((node) => {
node.value.body.unshift(ReactImport)
})
}
export default function transformer(file, api, options) {
const j = api.jscodeshift
const root = j(file.source)
const hasReactImport = (r) => {
return (
r.find(j.ImportDefaultSpecifier, {
local: {
type: 'Identifier',
name: 'React',
},
}).length > 0
)
}
const hasReactVariableUsage = (r) => {
return (
r.find(j.MemberExpression, {
object: {
type: 'Identifier',
name: 'React',
},
}).length > 0
)
}
if (hasReactImport(root)) {
return
}
if (hasReactVariableUsage(root)) {
addReactImport(j, root)
}
return root.toSource(options)
}