state-in-constructor.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @fileoverview Enforce the state initialization style to be either in a constructor or with a class property
  3. * @author Kanitkorn Sujautra
  4. */
  5. 'use strict';
  6. const astUtil = require('../util/ast');
  7. const componentUtil = require('../util/componentUtil');
  8. const docsUrl = require('../util/docsUrl');
  9. const report = require('../util/report');
  10. // ------------------------------------------------------------------------------
  11. // Rule Definition
  12. // ------------------------------------------------------------------------------
  13. const messages = {
  14. stateInitConstructor: 'State initialization should be in a constructor',
  15. stateInitClassProp: 'State initialization should be in a class property',
  16. };
  17. /** @type {import('eslint').Rule.RuleModule} */
  18. module.exports = {
  19. meta: {
  20. docs: {
  21. description: 'Enforce class component state initialization style',
  22. category: 'Stylistic Issues',
  23. recommended: false,
  24. url: docsUrl('state-in-constructor'),
  25. },
  26. messages,
  27. schema: [{
  28. enum: ['always', 'never'],
  29. }],
  30. },
  31. create(context) {
  32. const option = context.options[0] || 'always';
  33. return {
  34. 'ClassProperty, PropertyDefinition'(node) {
  35. if (
  36. option === 'always'
  37. && !node.static
  38. && node.key.name === 'state'
  39. && componentUtil.getParentES6Component(context, node)
  40. ) {
  41. report(context, messages.stateInitConstructor, 'stateInitConstructor', {
  42. node,
  43. });
  44. }
  45. },
  46. AssignmentExpression(node) {
  47. if (
  48. option === 'never'
  49. && componentUtil.isStateMemberExpression(node.left)
  50. && astUtil.inConstructor(context, node)
  51. && componentUtil.getParentES6Component(context, node)
  52. ) {
  53. report(context, messages.stateInitClassProp, 'stateInitClassProp', {
  54. node,
  55. });
  56. }
  57. },
  58. };
  59. },
  60. };