Skip to content

build: add tslint rule to enforce OnPush change detection #5707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/lib/checkbox/checkbox.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -887,12 +887,12 @@ class CheckboxWithFormDirectives {
}

/** Simple test component with multiple checkboxes. */
@Component(({
@Component({
template: `
<md-checkbox>Option 1</md-checkbox>
<md-checkbox>Option 2</md-checkbox>
`
}))
})
class MultipleCheckboxes { }


Expand Down
46 changes: 46 additions & 0 deletions tools/tslint-rules/onPushChangeDetectionRule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const Lint = require('tslint');
const ERROR_MESSAGE = 'Components must use OnPush change detection.';

/**
* Rule that enforces that OnPush change detection is used on all @Component declarations.
* Files can be whitelisted via `"on-push-change-detection": [true, "\.spec\.ts$"]`.
*/
class Rule extends Lint.Rules.AbstractRule {
apply(file) {
return this.applyWithWalker(new Walker(file, this.getOptions()));
}
}

class Walker extends Lint.RuleWalker {
constructor(file, options) {
super(...arguments);

// Whitelist with regular expressions to use when determining which files to lint.
const whitelist = options.ruleArguments;

// Whether the file should be checked at all.
this._enabled = !whitelist.length || whitelist.some(p => new RegExp(p).test(file.fileName));
}

visitClassDeclaration(node) {
if (!this._enabled || !node.decorators) return;

node.decorators
.map(decorator => decorator.expression)
.filter(expression => expression.expression.getText() === 'Component')
.filter(expression => expression.arguments.length && expression.arguments[0].properties)
.forEach(expression => {
const hasOnPushChangeDetection = expression.arguments[0].properties.some(prop => {
const value = prop.initializer.getText();
return prop.name.getText() === 'changeDetection' && value.endsWith('.OnPush');
});

if (!hasOnPushChangeDetection) {
this.addFailureAtNode(expression.parent, ERROR_MESSAGE);
}
});
}

}

exports.Rule = Rule;
4 changes: 4 additions & 0 deletions tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@
"src/lib",
"src/cdk"
],
"on-push-change-detection": [
true,
"(lib|cdk)\/((?!spec.ts).)*.ts$"
],
"one-line": [
true,
"check-catch",
Expand Down