|
export default function transformer(file, api) { |
|
const j = api.jscodeshift; |
|
|
|
const root = j(file.source) |
|
|
|
/** |
|
* Returns the styled import identifier. |
|
* Creates and inserts the identifier if it's not already defined. |
|
*/ |
|
const getStyledImport = () => { |
|
const defaultIdentifier = j.identifier('styled') |
|
const styledImport = root.find(j.ImportDeclaration, { |
|
source: { |
|
type: 'Literal', |
|
value: 'styled-components', |
|
}, |
|
}) |
|
|
|
if (styledImport.size() === 0) { |
|
// Don't have an import? Add one and return the identifier. |
|
root |
|
.find(j.Program) |
|
.forEach(p => { |
|
p.value.body.unshift(j.importDeclaration( |
|
[j.importDefaultSpecifier(defaultIdentifier)], |
|
j.literal('styled-components') |
|
)) |
|
}) |
|
return defaultIdentifier |
|
} else if (styledImport.size() === 1) { |
|
const defaultImport = styledImport.find(j.ImportDefaultSpecifier) |
|
if (defaultImport.size() > 0) { |
|
// have a default import? use its value! |
|
return defaultImport.get().value.local |
|
} else { |
|
// add one to existing import. |
|
styledImport.forEach(p => { |
|
p.value.specifiers.unshift( |
|
j.importDefaultSpecifier(defaultIdentifier) |
|
) |
|
}) |
|
return defaultIdentifier |
|
} |
|
} |
|
} |
|
|
|
// Find all Component.extend`` references |
|
const extendRefs = root |
|
.find(j.TaggedTemplateExpression, { |
|
tag: { |
|
type: 'MemberExpression', |
|
property: { |
|
type: 'Identifier', |
|
name: 'extend', |
|
}, |
|
}, |
|
}) |
|
|
|
if (extendRefs.length > 0) { |
|
const styledIdentifier = getStyledImport() |
|
|
|
// Convert all Component.extend`` references to styled(Component)`` |
|
extendRefs.forEach(p => |
|
p.value.tag = j.callExpression(j.identifier('styled'), [p.value.tag.object]) |
|
) |
|
} |
|
|
|
return root.toSource(); |
|
} |