Skip to content

Commit

Permalink
check if node is prop-type package
Browse files Browse the repository at this point in the history
  • Loading branch information
TildaDares committed Jul 9, 2022
1 parent bba712f commit 1636884
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/rules/forbid-prop-types.js
Expand Up @@ -60,6 +60,19 @@ module.exports = {
const configuration = context.options[0] || {};
const checkContextTypes = configuration.checkContextTypes || false;
const checkChildContextTypes = configuration.checkChildContextTypes || false;
let propTypesPackageName = null;
let reactPackageName = null;

function isPropTypesPackage(node) {
return (
node.type === 'Identifier'
&& node.name === propTypesPackageName
) || (
node.type === 'MemberExpression'
&& node.property.name === 'PropTypes'
&& node.object.name === reactPackageName
);
}

function isForbidden(type) {
const forbid = configuration.forbid || DEFAULTS;
Expand Down Expand Up @@ -157,6 +170,26 @@ module.exports = {
}

return {
ImportDeclaration(node) {
if (node.source && node.source.value === 'prop-types') { // import PropType from "prop-types"
if (node.specifiers.length > 0) {
propTypesPackageName = node.specifiers[0].local.name;
}
} else if (node.source && node.source.value === 'react') { // import { PropTypes } from "react"
if (node.specifiers.length > 0) {
reactPackageName = node.specifiers[0].local.name; // guard against accidental anonymous `import "react"`
}
if (node.specifiers.length >= 1) {
const propTypesSpecifier = node.specifiers.find((specifier) => (
specifier.imported && specifier.imported.name === 'PropTypes'
));
if (propTypesSpecifier) {
propTypesPackageName = propTypesSpecifier.local.name;
}
}
}
},

'ClassProperty, PropertyDefinition'(node) {
if (
!propsUtil.isPropTypesDeclaration(node)
Expand All @@ -183,6 +216,7 @@ module.exports = {
CallExpression(node) {
if (
node.callee.object
&& !isPropTypesPackage(node.callee.object)
&& !propsUtil.isPropTypesDeclaration(node.callee)
&& node.callee.object.name !== 'PropTypes'
) {
Expand Down

0 comments on commit 1636884

Please sign in to comment.