Skip to content

Instantly share code, notes, and snippets.

@knoopx
Last active February 9, 2022 12:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save knoopx/9bf6c0cbcdeb31c64822d0eb6340026a to your computer and use it in GitHub Desktop.
Save knoopx/9bf6c0cbcdeb31c64822d0eb6340026a to your computer and use it in GitHub Desktop.
codemod - rewrite class methods as arrow function properties
const IGNORE = [
'constructor',
'componentDidMount',
'componentDidUpdate',
'componentWillReceiveProps',
'componentWillMount',
'componentWillUpdate',
'componentWillUnmount',
'getChildContext',
'getDefaultProps',
'getInitialState',
'render',
'shouldComponentUpdate',
]
module.exports = function (file, api) {
const j = api.jscodeshift
const withComments = (to, from) => {
to.comments = from.comments
return to
}
const createArrowFunctionExpression = (fn) => {
const arrowFunc = j.arrowFunctionExpression(fn.params, fn.body, false)
arrowFunc.returnType = fn.returnType
arrowFunc.defaults = fn.defaults
arrowFunc.rest = fn.rest
arrowFunc.async = fn.async
return arrowFunc
}
const createArrowProperty = prop => withComments(
j.classProperty(
j.identifier(prop.key.name),
createArrowFunctionExpression(prop),
null,
false,
),
prop,
)
const root = j(file.source)
const methods = root
.find(j.ClassMethod)
.filter(path => path.value.kind === 'method')
.filter(path => !IGNORE.includes(path.value.key.name))
methods.replaceWith(m => createArrowProperty(m.node))
return root.toSource()
}
jscodeshift -t class-methods-to-arrow-function-props.js.js --extensions js,jsx --parser babylon --parser-config ./parser-config.json src/
{
"sourceType": "module",
"allowImportExportEverywhere": true,
"allowReturnOutsideFunction": true,
"startLine": 1,
"tokens": true,
"plugins": [
["flow", { "all": true }],
"flowComments",
"jsx",
"asyncGenerators",
"bigInt",
"classProperties",
"classPrivateProperties",
"classPrivateMethods",
["decorators", { "decoratorsBeforeExport": true }],
"doExpressions",
"dynamicImport",
"exportDefaultFrom",
"exportNamespaceFrom",
"functionBind",
"functionSent",
"importMeta",
"logicalAssignment",
"nullishCoalescingOperator",
"numericSeparator",
"objectRestSpread",
"optionalCatchBinding",
"optionalChaining",
["pipelineOperator", { "proposal": "minimal" }],
"throwExpressions"
]
}
@kud
Copy link

kud commented Nov 20, 2020

typo, it's jscodeshift -t class-methods-to-arrow-function-props.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment