Created
March 13, 2018 10:01
-
-
Save tkers/ea4fb1d699adb243b3f82b5ee34d4cae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Moves this.state assignment in constructor to class property | |
Run with codeshift: | |
jscodeshift -t ./constructor-state-to-class-property.js --extensions js,jsx --ignore-pattern 'node_modules' src/ | |
*/ | |
export default function transformer(file, api) { | |
const j = api.jscodeshift | |
const root = j(file.source) | |
root | |
.find(j.ClassDeclaration) | |
.find(j.MethodDefinition, { kind: 'constructor' }) | |
.find(j.AssignmentExpression, { | |
left: { object: j.ThisExpression, property: { name: 'state' } } | |
}) | |
.forEach(stateAssignment => { | |
const idName = stateAssignment.node.left.property | |
const stateValue = stateAssignment.node.right | |
const stateProperty = j.classProperty(idName, stateValue, null, false) | |
j(stateAssignment) | |
.closest(j.ClassBody) | |
.get('body') | |
.insertAt(0, stateProperty) | |
j(stateAssignment).remove() | |
}) | |
return root.toSource() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment