Last active
December 14, 2016 18:30
-
-
Save andrey-skl/fb13ad432c22c89057c9d0722ee6d904 to your computer and use it in GitHub Desktop.
Converts arrow functions, mistakely used for controllers, factories and services, to normal function expressions. Example usage http://astexplorer.net/#/4JAWwc4Jmf/1
This file contains 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
//Usage: jscodeshift -t angular-arrows-to-fns.js <pathes to files> | |
var THING_TO_REPLACE = 'controller'; | |
module.exports = (file, api, options) => { | |
const j = api.jscodeshift; | |
const root = j(file.source); | |
return root | |
.find(j.ArrowFunctionExpression) | |
.filter(path => { | |
const isArgument = path.parentPath.name === 'arguments' && path.parentPath.value.indexOf(path.value) > -1; | |
if (!isArgument) { | |
return false; | |
} | |
const caller = path.parentPath | |
&& path.parentPath.parentPath | |
&& path.parentPath.parentPath.value.callee | |
&& path.parentPath.parentPath.value.callee.property | |
&& path.parentPath.parentPath.value.callee.property.name; | |
const isArgumentOfAngularStuff = path.parentPath.value[0].type === "Literal" | |
&& path.parentPath.value[1].type === "ArrowFunctionExpression" | |
&& caller === THING_TO_REPLACE; | |
return isArgument && isArgumentOfAngularStuff; | |
}) | |
.replaceWith(p => { | |
var body = p.value.body; | |
if (body.type !== 'BlockStatement') { | |
body = j.blockStatement([j.returnStatement(body)]); | |
} | |
//console.log(p.value.params) | |
return j.functionExpression(j.identifier(THING_TO_REPLACE), p.value.params, body); | |
}). | |
toSource(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment