forked from jsx-eslint/eslint-plugin-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequire-default-props.js
95 lines (80 loc) · 2.91 KB
/
require-default-props.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* @fileOverview Enforce a defaultProps definition for every prop that is not a required prop.
* @author Vitor Balocco
*/
'use strict';
const Components = require('../util/Components');
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Enforce a defaultProps definition for every prop that is not a required prop.',
category: 'Best Practices',
url: docsUrl('require-default-props')
},
schema: [{
type: 'object',
properties: {
forbidDefaultForRequired: {
type: 'boolean'
}
},
additionalProperties: false
}]
},
create: Components.detect((context, components) => {
const configuration = context.options[0] || {};
const forbidDefaultForRequired = configuration.forbidDefaultForRequired || false;
/**
* Reports all propTypes passed in that don't have a defaultProps counterpart.
* @param {Object[]} propTypes List of propTypes to check.
* @param {Object} defaultProps Object of defaultProps to check. Keys are the props names.
* @return {void}
*/
function reportPropTypesWithoutDefault(propTypes, defaultProps) {
// If this defaultProps is "unresolved", then we should ignore this component and not report
// any errors for it, to avoid false-positives with e.g. external defaultProps declarations or spread operators.
if (defaultProps === 'unresolved') {
return;
}
Object.keys(propTypes).forEach((propName) => {
const prop = propTypes[propName];
if (prop.isRequired) {
if (forbidDefaultForRequired && defaultProps[propName]) {
context.report({
node: prop.node,
message: 'propType "{{name}}" is required and should not have a defaultProps declaration.',
data: {name: propName}
});
}
return;
}
if (defaultProps[propName]) {
return;
}
context.report({
node: prop.node,
message: 'propType "{{name}}" is not required, but has no corresponding defaultProps declaration.',
data: {name: propName}
});
});
}
// --------------------------------------------------------------------------
// Public API
// --------------------------------------------------------------------------
return {
'Program:exit': function () {
const list = components.list();
Object.keys(list).filter(component => list[component].declaredPropTypes).forEach((component) => {
reportPropTypesWithoutDefault(
list[component].declaredPropTypes,
list[component].defaultProps || {}
);
});
}
};
})
};