|
|
import type { |
|
|
API, |
|
|
Collection, |
|
|
FileInfo, |
|
|
JSCodeshift, |
|
|
Options, |
|
|
} from 'jscodeshift' |
|
|
import { createParserFromPath } from '../lib/parser' |
|
|
|
|
|
function addReactImport(j: JSCodeshift, root: Collection) { |
|
|
|
|
|
|
|
|
|
|
|
const ReactDefaultSpecifier = j.importDefaultSpecifier(j.identifier('React')) |
|
|
|
|
|
|
|
|
|
|
|
const originalReactImport = root.find(j.ImportDeclaration, { |
|
|
source: { |
|
|
value: 'react', |
|
|
}, |
|
|
}) |
|
|
if (originalReactImport.length > 0) { |
|
|
|
|
|
if (originalReactImport.find(j.ImportDefaultSpecifier).length > 0) { |
|
|
return |
|
|
} |
|
|
|
|
|
|
|
|
originalReactImport.forEach((node) => { |
|
|
node.value.specifiers.unshift(ReactDefaultSpecifier) |
|
|
}) |
|
|
return |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const ReactImport = j.importDeclaration( |
|
|
[ReactDefaultSpecifier], |
|
|
j.stringLiteral('react') |
|
|
) |
|
|
|
|
|
|
|
|
const Program = root.find(j.Program) |
|
|
|
|
|
Program.forEach((node) => { |
|
|
node.value.body.unshift(ReactImport) |
|
|
}) |
|
|
} |
|
|
|
|
|
export default function transformer( |
|
|
file: FileInfo, |
|
|
_api: API, |
|
|
options: Options |
|
|
) { |
|
|
const j = createParserFromPath(file.path) |
|
|
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) |
|
|
} |
|
|
|