|
| 1 | +import { API, FileInfo, Options } from 'jscodeshift'; |
| 2 | + |
| 3 | +export default function transformer( |
| 4 | + file: FileInfo, |
| 5 | + { jscodeshift: j }: API, |
| 6 | + options: Options, |
| 7 | +) { |
| 8 | + const removePath = path => j(path).remove(); |
| 9 | + |
| 10 | + // Obj.proptypes = { ... }; |
| 11 | + const isAssigningPropTypes = e => |
| 12 | + e.node.left && |
| 13 | + e.node.left.property && |
| 14 | + e.node.left.property.name === 'propTypes'; |
| 15 | + |
| 16 | + // import PropTypes from 'prop-types'; |
| 17 | + const isImportingFromPropTypes = e => |
| 18 | + e.node.source && e.node.source.value === 'prop-types'; |
| 19 | + |
| 20 | + // require('prop-types'); |
| 21 | + const isRequiringFromPropTypes = e => |
| 22 | + e.node.init && |
| 23 | + e.node.init.callee && |
| 24 | + e.node.init.callee.name === 'require' && |
| 25 | + e.node.init.arguments[0].value === 'prop-types'; |
| 26 | + |
| 27 | + // _defineProperty(obj, 'propTypes', { ... }); |
| 28 | + const isDefiningPropType = e => |
| 29 | + e.node.expression && |
| 30 | + e.node.expression.callee && |
| 31 | + e.node.expression.callee.name === '_defineProperty' && |
| 32 | + e.node.expression.arguments && |
| 33 | + e.node.expression.arguments[1] && |
| 34 | + e.node.expression.arguments[1].original && |
| 35 | + e.node.expression.arguments[1].original.value === 'propTypes'; |
| 36 | + |
| 37 | + // { propTypes: { foo: PropTypes.string } }; |
| 38 | + const isObjectProperty = e => |
| 39 | + e.node.key && |
| 40 | + e.node.key.name === 'propTypes' && |
| 41 | + e.node.value && |
| 42 | + e.node.value.type === 'ObjectExpression'; |
| 43 | + |
| 44 | + const withoutAssignment = j(file.source) |
| 45 | + .find(j.AssignmentExpression) |
| 46 | + .filter(isAssigningPropTypes) |
| 47 | + .forEach(removePath) |
| 48 | + .toSource(); |
| 49 | + |
| 50 | + const withoutImport = j(withoutAssignment) |
| 51 | + .find(j.ImportDeclaration) |
| 52 | + .filter(isImportingFromPropTypes) |
| 53 | + .forEach(removePath) |
| 54 | + .toSource(); |
| 55 | + |
| 56 | + const withoutRequire = j(withoutImport) |
| 57 | + .find(j.VariableDeclarator) |
| 58 | + .filter(isRequiringFromPropTypes) |
| 59 | + .forEach(removePath) |
| 60 | + .toSource(); |
| 61 | + |
| 62 | + const withoutDefineProperty = j(withoutRequire) |
| 63 | + .find(j.ExpressionStatement) |
| 64 | + .filter(isDefiningPropType) |
| 65 | + .forEach(removePath) |
| 66 | + .toSource(); |
| 67 | + |
| 68 | + const withoutObjectProperty = j(withoutDefineProperty) |
| 69 | + .find(j.Property) |
| 70 | + .filter(isObjectProperty) |
| 71 | + .forEach(removePath); |
| 72 | + |
| 73 | + return withoutObjectProperty.toSource(options.printOptions); |
| 74 | +} |
0 commit comments