Skip to content

Commit

Permalink
Add React.PureComponent support to require-optimization rule
Browse files Browse the repository at this point in the history
  • Loading branch information
yannickcr committed Aug 3, 2016
1 parent c670bb2 commit 8b567a6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
20 changes: 19 additions & 1 deletion lib/rules/require-optimization.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
'use strict';

var Components = require('../util/Components');
var pragmaUtil = require('../util/pragma');

module.exports = {
meta: {
Expand Down Expand Up @@ -33,6 +34,10 @@ module.exports = {
var configuration = context.options[0] || {};
var allowDecorators = configuration.allowDecorators || [];

var pragma = pragmaUtil.getFromContext(context);
var pureComponentRegExp = new RegExp('^(' + pragma + '\\.)?PureComponent$');
var sourceCode = context.getSourceCode();

/**
* Checks to see if our component is decorated by PureRenderMixin via reactMixin
* @param {ASTNode} node The AST node being checked.
Expand Down Expand Up @@ -84,6 +89,19 @@ module.exports = {
return false;
};

/**
* Checks to see if our component extends React.PureComponent
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if node extends React.PureComponent, false if not.
*/
var isPureComponent = function (node) {
if (node.superClass) {
return pureComponentRegExp.test(sourceCode.getText(node.superClass));
}

return false;
};

/**
* Checks if we are declaring a shouldComponentUpdate method
* @param {ASTNode} node The AST node being checked.
Expand Down Expand Up @@ -150,7 +168,7 @@ module.exports = {
},

ClassDeclaration: function (node) {
if (!(hasPureRenderDecorator(node) || hasCustomDecorator(node))) {
if (!(hasPureRenderDecorator(node) || hasCustomDecorator(node) || isPureComponent(node))) {
return;
}
markSCUAsDeclared(node);
Expand Down
16 changes: 16 additions & 0 deletions tests/lib/rules/require-optimization.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,22 @@ ruleTester.run('react-require-optimization', rule, {
parser: 'babel-eslint',
options: [{allowDecorators: ['renderPure', 'pureRender']}],
parserOptions: parserOptions
}, {
code: [
'import React from "react";' +
'class YourComponent extends React.PureComponent {}'
].join('\n'),
parser: 'babel-eslint',
options: [{allowDecorators: ['renderPure', 'pureRender']}],
parserOptions: parserOptions
}, {
code: [
'import React, {PureComponent} from "react";' +
'class YourComponent extends PureComponent {}'
].join('\n'),
parser: 'babel-eslint',
options: [{allowDecorators: ['renderPure', 'pureRender']}],
parserOptions: parserOptions
}],

invalid: [{
Expand Down

0 comments on commit 8b567a6

Please sign in to comment.