state-in-constructor.js
1.57 KB
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
/**
* @fileoverview Enforce the state initialization style to be either in a constructor or with a class property
* @author Kanitkorn Sujautra
*/
'use strict';
const Components = require('../util/Components');
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'State initialization in an ES6 class component should be in a constructor',
category: 'Stylistic Issues',
recommended: false,
url: docsUrl('state-in-constructor')
},
schema: [{
enum: ['always', 'never']
}]
},
create: Components.detect((context, components, utils) => {
const option = context.options[0] || 'always';
return {
ClassProperty(node) {
if (
option === 'always'
&& !node.static
&& node.key.name === 'state'
&& utils.getParentES6Component()
) {
context.report({
node,
message: 'State initialization should be in a constructor'
});
}
},
AssignmentExpression(node) {
if (
option === 'never'
&& utils.isStateMemberExpression(node.left)
&& utils.inConstructor()
&& utils.getParentES6Component()
) {
context.report({
node,
message: 'State initialization should be in a class property'
});
}
}
};
})
};