From 46e6116d80de0a45cc30162d972095a39dc13781 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Thu, 7 Jun 2018 07:55:16 +0200 Subject: [PATCH] build: add tslint rule to enforce consistent rxjs imports (#11629) Adds a small tslint rule that will help us catch cases like [this one](https://github.com/angular/material2/blob/master/src/demo-app/virtual-scroll/virtual-scroll-demo.ts#L10), which can come up when the IDE auto-imports something from rjxs. --- .../virtual-scroll/virtual-scroll-demo.ts | 2 +- tools/tslint-rules/rxjsImportsRule.ts | 23 +++++++++++++++++++ tslint.json | 1 + 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 tools/tslint-rules/rxjsImportsRule.ts diff --git a/src/demo-app/virtual-scroll/virtual-scroll-demo.ts b/src/demo-app/virtual-scroll/virtual-scroll-demo.ts index 8b797703b3b..8aff47670d9 100644 --- a/src/demo-app/virtual-scroll/virtual-scroll-demo.ts +++ b/src/demo-app/virtual-scroll/virtual-scroll-demo.ts @@ -7,7 +7,7 @@ */ import {Component, ViewEncapsulation} from '@angular/core'; -import {BehaviorSubject} from 'rxjs/index'; +import {BehaviorSubject} from 'rxjs'; type State = { diff --git a/tools/tslint-rules/rxjsImportsRule.ts b/tools/tslint-rules/rxjsImportsRule.ts new file mode 100644 index 00000000000..c942e6c1970 --- /dev/null +++ b/tools/tslint-rules/rxjsImportsRule.ts @@ -0,0 +1,23 @@ +import * as ts from 'typescript'; +import * as Lint from 'tslint'; + +/** + * Rule that ensures that all rxjs imports come only from `rxjs` and `rxjs/operators`. + */ +export class Rule extends Lint.Rules.AbstractRule { + apply(sourceFile: ts.SourceFile) { + return this.applyWithWalker(new Walker(sourceFile, this.getOptions())); + } +} + +class Walker extends Lint.RuleWalker { + visitImportDeclaration(node: ts.ImportDeclaration) { + const specifier = node.moduleSpecifier.getText().slice(1, -1); + + if (specifier.startsWith('rxjs') && specifier !== 'rxjs' && specifier !== 'rxjs/operators') { + this.addFailureAtNode(node, 'RxJS imports are only allowed from `rxjs` or `rxjs/operators`.'); + } + + super.visitImportDeclaration(node); + } +} diff --git a/tslint.json b/tslint.json index 6c91e04fa59..ff30b9385e5 100644 --- a/tslint.json +++ b/tslint.json @@ -98,6 +98,7 @@ "ts-loader": true, "no-exposed-todo": true, "setters-after-getters": true, + "rxjs-imports": true, "no-host-decorator-in-concrete": [ true, "HostBinding",