Skip to content

Instantly share code, notes, and snippets.

@lund0n
Last active October 1, 2018 23:03
Show Gist options
  • Save lund0n/655eefaf11beac907d67b31d5225d4f4 to your computer and use it in GitHub Desktop.
Save lund0n/655eefaf11beac907d67b31d5225d4f4 to your computer and use it in GitHub Desktop.
Converts all styled-components `Component.extend` calls to `styled(Component)` calls
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment