RxJS tslint 規則與推薦配置
本文推薦一些和 RxJS 使用相關的規則,並做分級配置。其中,Force 表示強制,Recommend 表示推薦,Optional 表示可選。
Force: no-unused-variable
在代碼中禁止未使用的 import 引入、變量、函數以及私有類成員等。
"no-unused-variable": [true, {"ignore-pattern": "^_"}]
tslint 規則描述 https://palantir.github.io/tslint/rules/no-unused-variable/
Force: Avoid takeUntil Leaks
防止由於不規範的 takeUntil
使用導致的 subscriptions 隱患。
"rxjs-no-unsafe-takeuntil": true,
場景解釋 https://ncjamieson.com/avoiding-takeuntil-leaks/
Recommend: Finnish Notation
強制開啓 functions, methods, parameters, properties 與 variables 五項的命名規範。
"rxjs-finnish": { "options": [ { "functions": true, "methods": true, "parameters": true, "properties": true, "variables": true } ], "severity": "error" },
場景解釋 https://medium.com/@benlesh/observables-and-finnish-notation-df8356ed1c9b
Recommend: Async Subscribe
不允許將 async 方法傳入 subscribe。
"rxjs-no-async-subscribe": true,
Recommend: No ignored notifier/observable/subscribe
一些禁止忽略的規則,比如不允許忽視函數返回的 Observable,不允許不指定入參的調用 subscribe,禁止不是由 repeatWhen
與 retryWhen
notifier 組成的 Observable 等。
"rxjs-no-ignored-notifier": true, "rxjs-no-ignored-observable": true, "rxjs-no-ignored-subscribe": true,
Recommend: No redundant
禁止在已處於 complete 或者 error 狀態的 Observable 中傳遞無效的通知。
// 配置 "rxjs-no-redundant-notify": true, // 問題用法 new Observable<number>(observer => { observer.complete(); observer.next(42); ~~~~ [no-redundant-notify] }),
Recommend: No subclass
不允許將 RxJS class 子類化。
// 配置 "rxjs-no-subclass": true, // 問題用法 class GenericObservable<T> extends Observable<T> {} ~~~~~~~~~~~~~ [no-subclass]
Recommend: (un)subscribe
不允許在 Subject 實例上調用 unsubscribe 方法;不允許在 subscribe 方法中嵌套調用 subscribe。
"rxjs-no-subject-unsubscribe": true, "rxjs-no-nested-subscribe": true,
Recommend: Unbound methods
禁止在代碼中出現對未綁定的方法調用。
// 配置 "rxjs-no-unbound-methods": true, // 問題用法 const ob = of(1).pipe( map(this.map), ~~~~~~~~ [no-unbound-methods] )
Recommend: No create
不允許調用 Observable.create,用 new Observable 替代。
"rxjs-no-create": true,
Optional: Rules with NgRx
"rxjs-no-unsafe-first": true, "rxjs-no-unsafe-switchmap": true, "rxjs-no-unsafe-catch": true,
Optional: Switching to lettable operators
當使用 Lettable Operator 時,可以通過一些規則禁用其他的引入方法。
"rxjs-no-add": { "severity": "error" }, "rxjs-no-patched": { "severity": "error" }, "rxjs-no-operator": { "severity": "error" },
場景解釋 https://ncjamieson.com/understanding-lettable-operators/
Optional: rxjs-ban-operators
// 禁止使用指定的 operator 或者 observable "rxjs-ban-operators": { "options": [{ "concat": "Use the concat factory function", }], "severity": "error" }