@odg/eslint-config
v2.0.2
Published
Linter for JavaScript And Typescript project
Downloads
289
Readme
Standard Code
- Introduction
- File Name Convention
- Semi Rule
- Quotes Rule
- Indent Rule
- Line Break Rule
- EOL last Rule
- Max Line Len Rule
- Camel Case Rule
- Strict
- Padded Block Rule
- Lines Between Class Members
- No Multi Assign Rule
- Explicit Member Accessibility Rule
- Default Param Last Rule
- Space Before Function Paren
- Exception Handled
- Array Space
- Key Word Space
- Space Format
- UTF-8 Only
- No Space in Parentheses
- No Multiple Space
- Useless String Concat
- No Self Assign
- Force Return Type
- Array Bracket Line
- Unused Vars
- Comma Spacing
- Comma Dangle
- Arrow Spacing
- Prefer Arrow Function
- Prefer Destructuring
- Arrow Function Body
- Arrow Function Parentheses
- Arrow Function No Break Line
- No Empty Block
- No Long Syntax
- Useless Parens
- Useless Boolean
- Useless Alias
- Return New line
- Comment Multi Line Prefer
- No throw Literal
- No Unreachable
- No Multiline String
- No Unsafe Assign
- Disallow Script Url
- Disallow Undefined
- Function Name
- Function Name Match
- No Use Future Reserved Words
- No Generator Without Yield
- Inverted Assertion Arguments
- Max Union Size
- No Redundant Optional
- Prefer Type Guard
- No Production Debug
- Unused Named Groups
- Get And Setters
- Function Style
- No Else Return
- No Console Spaces
- No Hex Escape
- Prefer Array Flat Map
- Prefer String Slice
- Prefer Modern DOM
- Prefer Prefix Number
- Numeric Separators Style
- Prefer Default Parame
- No Avoid Reverse
- Prefer Code Point
- Bool Param Default
- Class Name Convention
- Comma Or Logical Or Case
- No Constructor Bind
- No Thenable
- No Unreadable Iife
- Prefer Native Cast
- Prefer Logical Operator Over Ternary
- Prefer Event Target
- Prefer Object From Entries
- Prefer Array From Map
- Prefer Array Flat
- This Pattern
- Use Dot
- Use this
- Use IsNan
- Dot Object Format
- No Trailing Space
- Type Format
- Max Statements Per Line
- No Constant Condition
- No Debugger
- Not Duplicate Case
- Regex Block
- No Overwrite Exception
- No Extra Semi
- No Function Overwrite
- No Delete Var
- No Lone Blocks
- No Proto
- No Declare in Block
- No Nonoctal Decimal Escape
- No Import Absolute Path
- No Webpack Loader Syntax
- No Magic Number
- Security Negation
- Regex Space
- Array No Space
- Valid TypeOf
- Strict equality
- No Label
- Full Decimal Number
- No Global Overwrite
- Not Used New
- No New Function
- No Redeclare
- No Self Compare
- Loop Valid
- Useless Scape
- No Yoda
- No Undefined declare
- No New require
- No New Object
- No New Symbol
- Var Size
- Max Depth
- Max Params
- Max Statements
- Operator Assignment
- Require Yield
- Prefer Rest Params
- Symbol Description
- No Await Return
- Max Class Per File
- No Constructor Return
- Prefer Exponentiation Operator
- Prefer Object Spread
- Accessor Pairs
- Default Case Last
- Prefer Literals
- Useless Condition
- No Multiple Empty Line
- No Misused New
- No Semicolon Before spacing
- Disallow Type
- Disallow Empty Function
- Disallow Duplicate Imports
- Disallow Unnecessary Type
- Disallow Caller
- Disallow Underscore
- Disallow Param Reassign
- Prefer Const
- Array Type
- Disallow Await sync function
- Method Signature Style
- No Unnecessary Type Assertion
- No Unsafe Call
- No Var
- Operator Break-Line
- Generator Function Stars
- No Unsafe Optional Chaining
- Array Callback
- Space Types
- Curly
- Quote Props
- Brace Style
- Comma Style
- Object Break Line
- Object Curly Newline
- No Negative Condition
- No Duplicated Branches
- No Identical Functions
- No Inverted Boolean Check
- No Nested Switch
- No Nested Template Literals
- No Redundant Boolean
- Prefer Immediate Return
- Prefer Object Literal
- Prefer Single Boolean Return
- No Shadow
- Parentheses New Line
- No Func Call Spacing
- Array Element New Line
- Wrap Iife
- Disallow Template Tag Space
- No Space Spread
- Inline IF
- New Instance Use Parentheses
- Logical Assignment Operators
- No With
- Promise Rules
- Import
- Documentation
- Regex Rules
- No Optional With Assertion
- No Control Character
- No Dupe Condition
- No Empty Alternative
- No Empty Capturing Group
- No Empty Character Class
- No Empty Group
- No Empty Look Rounds Assertion
- No Escape Backspace
- No Invalid Regexp
- No Lazy Ends
- No Misleading Unicode Character
- No Optional Assertion
- No Potentially Useless Back Reference
- No Useless Assertions
- No Useless Back Reference
- No Useless Dollar Replacements
- Strict Regex
- Confusing Quantifier
- Control Character Escape
- Negation
- No Dupe Characters Character Class
- No Invisible Character
- No Legacy Features
- No Non Standard Flag
- No Obscure Range
- No Trivially Nested Quantifier
- No Unused Capturing Group
- No Useless Character Class
- No Useless Flag
- No Useless Lazy
- No Useless Quantifier
- No Useless Range
- No Useless Two Num Quantifier
- No Zero Quantifier
- Optimal LookAround Quantifier
- Optimal Quantifier Concatenation
- Prefer Quantifier
- Prefer Range
- Sort Alternatives
- Hexadecimal Escape
- Match Any
- No Useless Escape
- No Useless Non Capturing Group
- Prefer Character Class
- Prefer D
- Prefer Plus
- Prefer Question Quantifier
- Prefer Star Quantifier
- Prefer Unicode Code Point Escapes
- Prefer W
- Sort Character Class Elements
- Sort Flags
- Prefer Named Capture Group
- Prefer Regexp Exec
- Existing Groups
- No Misleading Capturing Group
- No Extra Lookaround Assertions
- Security
- Eval Disabled
- Detect Unsafe Regex
- Buffer No Assert
- No Exec Child Process
- No Mustache Scape
- No Csrf Before Method Override
- No Literal Fs Filename
- No Pseudo Random Bytes
- Prevent Secret Token
- Prevent Literal Code
- No Import Dynamic
- Security SSL
- Security Encrypt Access
- Certificate Transparency
- No Log confidential information
- Content Length
- Anti Trojan Source No Bidi
- Cookie Httponly
- Protect XSS Render
- Force Integrity
- DNS prefetching
- No Prototype Builtins
- File Permissions
- File Upload
- Frame Ancestors
- Hashing Insecurity
- Hidden Files
- No Dynamic Delete
- Cors
- Csrf
- Aws Security
- Security Cookie
- Insecure Cookie
- No Clear Text Protocols
- Insecure Jwt Token
- No Hardcoded Credentials
- No Hardcoded ip
- No Os Command From Path
- No Unsafe Unzip
- Sockets
- Helmet Security
- Unverified Certificate
- Sql Queries
- Catch Error Name
- Consistent Destructured
- Consistent Function Scope
- Exception With Message
- Escape Case
- New For Builtin
- No Abusive Eslint Disable
- Prefer for-of
- No Array Push Push
- No Await Chased
- No Document Cookie
- No Empty File
- No Instance Of Array
- No Invalid Remove Event Listener
- No Lonely If
- No Nested Ternary
- No New Buffer
- No This Assignment
- No Useless Fallback In Spread
- No Useless Length Check
- No Useless Spread
- No Useless Switch Case
- No Useless Undefined
- Prefer Add Event Listener
- Prefer Array Find
- Prefer Array Index Of
- Prefer Array Some
- Prefer Dom Node Append
- Prefer Include
- Prefer Keyboard Event Key
- Prefer Negative Index
- Prefer Optional Catch Binding
- Prefer Prototype Methods
- Prefer Query Selector
- Prefer Regexp Test
- Prefer Spread
- Prefer String Replace All
- Prefer String Starts Ends With
- Prefer String Trim Start End
- Prefer Switch
- Prefer Ternary
- Multiline Ternary Multiple
- Prevent Abbreviations
- Consistent Relative URL
- Require Array Join Separator
- Require Number To Fixed Digits Argument
- Template String Indent
- Adjacent Overload Signatures
- Ban Ts Comment
- Ban Tslint Comment
- Class Literal Property Style
- Consistent Generic Constructors
- Consistent Indexed Object Style
- Consistent Type Assertions
- Consistent Type Definitions
- Consistent Type Exports
- Consistent Type Imports
- Member Delimiter Style
- Member Ordering
- No Confusing Non Null Assertion
- No Extra Non Null Assertion
- No For In Array
- No Inferrable Type
- No This Alias
- Non Nullable Type Assertion Style
- Parameter Properties
- Prefer Enum Initializers
- Prefer Function Type
- Prefer Namespace Keyword
- Prefer Nullish Coalescing
- Prefer Optional Chain
- Prefer Readonly
- Prefer Reduce Type Parameter
- Promise Function Async
- Require Array Sort Compare
- Sort Type Constituents
- Space Before Blocks
- Performance
- Errors
- Construtor Super Invalid
- Getter Return
- No Class Assign
- No Compare Neg Zero
- Useless Loop
- No Loss Of Precision
- No Unsafe Argument
- No Dupe Class Members
- No Dupe Keys
- Import Default Not Fount
- Import Namespace
- No Self Import
- Export Name
- Import Namespace
- No Import Resolve
- Import Not Found
- JS Type
- No Invalid This
- No This Before Super
- No Obj Calls
- No Empty Pattern
- No Useless Computed Key
- Useless Call Code
- Useless Catch Code
- Useless Expression Code
- Useless Return Code
- Useless Construct Code
- No Use Before Define
- No Base To String
- Not IN Primitive type
- Useless String Operation
- Super Invocation
- No Useless Intersection
- Stateful Regex
- Possible Errors
- For Direction
- No Extra Bind
- No Template Curly In String
- No Dupe Else If
- No Unused Private Class Members
- No Constant Binary Expression
- No Unneeded Ternary
- No Unsafe Negation
- Text Encoding Identifier Case
- Arguments Order
- Assertions In Tests
- Test Multiple Possible Assert
- No Disable Timeout
- No Empty Static Block
- No Fallthrough
- No Octal
- Octal Scape
- No Global Assign
- No Case Declarations
- No Confusing Void Expression
- No Duplicate Enum Values
- No Floating Promises
- No Invalid Void Type
- No Non Null Asserted Nullish Coalescing
- No Non Null Asserted Optional Chain
- No Unsafe Declaration Merging
- No Useless Empty Export
- Restrict Template Expressions
- Return Await Try Catch
- Switch Exhaustiveness Check
- Index Of Compare To Positive Number
- No Invariant Returns
- Inconsistent Function Call
- Duplicate Conditions
- Redundant Type Aliases
- No Element Overwrite
- No Empty Collection
- No Extra Arguments
- No Identical Expressions
- No Ignored Return
- No Use Of Empty Return Value
- No Collection Size Mischeck
- No Gratuitous Expressions
- No Unused Collection
- No Inconsistent Docblock
- YAML / JSON
Introduction
Installation
Add dependence to package.json
npm install eslint @odg/eslint-config
# or
yarn add -D eslint @odg/eslint-config
Add extends in your .eslintrc
file
{
"extends": [ "@odg" ]
}
Add script in your package.json
file
{
"scripts": {
"lint": "eslint --ext .js,.jsx,.ts,.tsx,.json,.jsonc,.json5,.yml,.yaml,.xml,.txt,.svg,.properties,.gradle,.java,.cpp,.c,.cs,.html,.css,.groovy,.gitignore,.npmignore,.toml,.env,.example,.sample,.ini,.php,.bat,.powershell,.ps1,.sh,.bash,.eslintrc",
}
}
Test: npm run lint
or yarn lint
File Name Convention
File Name Convention
https://github.com/selaux/eslint-plugin-filenames
👍 Examples of correct code
// File name Foo.ts
export default class Foo {
}
👎 Examples of incorrect code
// File name FooClass.ts
export default class Foo {
}
Semi Rule
Requires semicolons at the end of statements
https://eslint.org/docs/rules/semi#semi https://eslint.org/docs/rules/semi-style
👍 Examples of correct code
var name = "ODG";
object.method = function() {
// ...
};
class Foo {
bar = 1;
}
foo();
[1, 2, 3].forEach(bar);
for (
var i = 0;
i < 10;
++i
) {
foo();
}
class C {
static {
foo();
}
}
👎 Examples of incorrect code
var name = "ODG"
object.method = function() {
// ...
}
class Foo {
bar = 1
}
foo()
;[1, 2, 3].forEach(bar)
for (
var i = 0
; i < 10
; ++i
) {
foo()
}
class C {
static {
foo()
;bar()
}
}
Quotes Rule
Requires the use of double quotes wherever possible
Enforces the use of double quotes for all JSX attribute values that don’t contain a double quote.
https://eslint.org/docs/rules/quotes https://eslint.org/docs/rules/jsx-quotes
👍 Examples of correct code
var double = "double";
var backtick = `back
tick`; // backticks are allowed due to newline
var backtick = tag`backtick`;
👎 Examples of incorrect code
var single = 'single';
var unescaped = 'a string containing "double" quotes';
var backtick = `back\ntick`; // you can use \n in single or double quoted strings
Indent Rule
Requires indent with 4 spaces Tabs Disallow
https://eslint.org/docs/rules/indent#indent https://sonarsource.github.io/rspec/#/rspec/S3973/javascript https://eslint.org/docs/latest/rules/no-tabs https://eslint.org/docs/latest/rules/no-mixed-spaces-and-tabs
👍 Examples of correct code
if (a) {
b=c;
function foo(d) {
e=f;
}
}
👎 Examples of incorrect code
if (a) {
b=c;
function foo(d) {
e=f;
}
}
Line Break Rule
Enforces the usage of Unix line endings: \n
for LF.
https://eslint.org/docs/rules/linebreak-style#linebreak-style
👍 Examples of correct code
var a = 'a'; // \n
👎 Examples of incorrect code
var a = 'a'; // \r\n
EOL last Rule
Force empty end line
https://eslint.org/docs/rules/eol-last#eol-last
👍 Examples of correct code
function doSmth() {
var foo = 2;
} // \n
👎 Examples of incorrect code
function doSmth() {
var foo = 2;
}
Max Line Len Rule
Max line len is 120
https://eslint.org/docs/rules/max-len#max-len
👍 Examples of correct code
var foo = {
"bar": "This is a bar.",
"baz": { "qux": "This is a qux" },
"difficult": "to read",
};
👎 Examples of incorrect code
var foo = { "bar": "This is a bar.", "baz": { "qux": "This is a qux" }, "difficult": "to read" };
Camel Case Rule
Force use camel case variable
https://eslint.org/docs/rules/camelcase#camelcase
👍 Examples of correct code
import { no_camelcased as camelCased } from "external-module";
var myFavoriteColor = "#112C85";
var _myFavoriteColor = "#112C85";
var myFavoriteColor_ = "#112C85";
var MY_FAVORITE_COLOR = "#112C85";
👎 Examples of incorrect code
import { no_camelcased } from "external-module"
var my_favorite_color = "#112C85";
function do_something() {
// ...
}
Strict
A strict mode directive is a "use strict" literal at the beginning of a script or function body. It enables strict mode semantics.
https://eslint.org/docs/latest/rules/strict
👍 Examples of correct code
"use strict";
function foo() {
}
👎 Examples of incorrect code
function foo() {
}
Padded Block Rule
force empty line in blocks
https://eslint.org/docs/rules/padded-blocks#padded-blocks
{
"classes": "always",
"blocks": "never",
"switches": "never",
}
👍 Examples of correct code
class ClassName {
variable = 1;
}
switch (a) {
case 0: foo();
}
if (a) {
a = b;
}
👎 Examples of incorrect code
class ClassName {
variable = 1;
}
class ClassName {
variable = 1;
}
switch (a) {
case 0: foo();
}
if (a) {
a = b;
}
Lines Between Class Members
Enforces consistent spacing before function parenthesis.
https://eslint.org/docs/rules/lines-between-class-members#lines-between-class-members https://eslint.style/rules/ts/lines-between-class-members
👍 Examples of correct code
class MyClass {
x;
foo() {
//...
}
bar() {
//...
}
}
👎 Examples of incorrect code
class MyClass {
x;
foo() {
//...
}
bar() {
//...
}
}
No Multi Assign Rule
Chaining the assignment of variables can lead to unexpected results and be difficult to read. Disabled.
https://eslint.org/docs/rules/no-multi-assign#no-multi-assign
👍 Examples of correct code
var a = 5;
var b = 5;
var c = 5;
const foo = "baz";
const bar = "baz";
let a = c;
let b = c;
class Foo {
a = 10;
b = 10;
}
a = "quux";
b = "quux";
👎 Examples of incorrect code
var a = b = c = 5;
const foo = bar = "baz";
let a =
b =
c;
class Foo {
a = b = 10;
}
a = b = "quux";
Explicit Member Accessibility Rule
Force specific public/private or protected visibility
{
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}
👍 Examples of correct code
class ClassName {
public a = 1;
protected c = 2;
private b = 3;
}
👎 Examples of incorrect code
class ClassName {
a = 1;
c = 2;
b = 3;
}
Default Param Last Rule
Enforces default parameters to be last.
https://eslint.org/docs/rules/default-param-last#default-param-last
👍 Examples of correct code
function f(a = 0) {}
function f(a: number, b = 0) {}
function f(a: number, b?: number) {}
function f(a: number, b?: number, c = 0) {}
function f(a: number, b = 0, c?: number) {}
class Foo {
constructor(public a, private b = 0) {}
}
class Foo {
constructor(public a, private b?: number) {}
}
👎 Examples of incorrect code
function f(a = 0, b: number) {}
function f(a: number, b = 0, c: number) {}
function f(a: number, b?: number, c: number) {}
class Foo {
constructor(public a = 10, private b: number) {}
}
class Foo {
constructor(public a?: number, private b: number) {}
}
Space Before Function Paren
Enforces default parameters to be last.
https://eslint.org/docs/latest/rules/space-before-function-paren https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/space-before-function-paren.md https://eslint.style/rules/ts/space-before-function-paren
👍 Examples of correct code
foo(function() {
})
function foo() {
}
(async () => {})()
👎 Examples of incorrect code
foo(function () {
})
function foo () {
}
(async() => {})()
Exception Handled
Enforces callback error handling.
https://eslint.org/docs/rules/handle-callback-err https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/handle-callback-err.md
👍 Examples of correct code
function loadData (err, data) {
if (err) {
console.log(err.stack);
}
doSomething();
}
function loadData (exception, data) {
if (exception) {
console.log(exception);
}
doSomething();
}
function generateError (err) {
if (err) {
throw new Exception(err.message);
}
}
👎 Examples of incorrect code
function loadData (err, data) {
doSomething();
}
function loadData (exception, data) {
doSomething();
}
Class Name
This rule requires constructor names to begin with a capital letter.
https://eslint.org/docs/rules/new-cap
👍 Examples of correct code
var friend = new Person();
👎 Examples of incorrect code
var friend = new person();
var friend = Person();
Array Space
requires one or more spaces or newlines inside array brackets, and disallow space inside of computed properties.
https://eslint.org/docs/rules/array-bracket-spacing#array-bracket-spacing
https://eslint.org/docs/rules/computed-property-spacing#computed-property-spacing
👍 Examples of correct code
var arr = [ 'foo', 'bar' ];
var [ x, y ] = z;
var c = arr[0];
👎 Examples of incorrect code
var arr = ['foo', 'bar'];
var [x,y] = z;
var c = arr[ 0 ];
var c = object[ "foo" ];
var c = object["foo" ];
var c = object[ "foo"];
Key Word Space
Enforces consistent spacing before and after keywords.
https://eslint.org/docs/rules/keyword-spacing#keyword-spacing https://eslint.org/docs/rules/yield-star-spacing https://eslint.style/rules/ts/keyword-spacing
👍 Examples of correct code
if (foo) {
//...
} else if (bar) {
//...
} else {
//...
}
try {
} catch(e) {
// code ...
}
function *generator() {
yield *other();
}
👎 Examples of incorrect code
if(foo){
//...
}else if(bar){
//...
}else{
//...
}
try{
}catch(e){
// code ...
}
function*generator() {
yield*other();
}
function* generator() {
yield* other();
}
function * generator() {
yield * other();
}
Space Format
This rule enforces consistency regarding the spaces after
https://eslint.org/docs/rules/space-unary-ops#space-unary-ops
👍 Examples of correct code
a++;
++a;
--a;
a--;
async function foo() {
await bar;
}
if (!foo) {
}
const value = +"3";
👎 Examples of incorrect code
a ++;
++ a;
-- a;
a --;
async function foo() {
await(bar);
}
if (! foo) {
}
const value = + "3";
UTF-8 Only
Disallow the Unicode Byte Order Mark (BOM).
https://eslint.org/docs/rules/unicode-bom#unicode-bom
No Space in Parentheses
Disallows or enforce spaces inside of parentheses.
https://eslint.org/docs/rules/space-in-parens#space-in-parens
👍 Examples of correct code
foo();
foo('bar');
foo(/* bar */);
var foo = (1 + 2) * 3;
(function () { return 'bar'; }());
👎 Examples of incorrect code
foo( );
foo( 'bar');
foo('bar' );
foo( 'bar' );
foo( /* bar */ );
var foo = ( 1 + 2 ) * 3;
( function () { return 'bar'; }() );
No Multiple Space
Disallows multiple consecutive spaces.
https://eslint.org/docs/rules/no-multi-spaces#no-multi-spaces
👍 Examples of correct code
var a = 1;
if(foo === "bar") {}
a << b
var arr = [ 1, 2 ];
var a = [];
var baz = [];
a ? b : c
👎 Examples of incorrect code
var a = 1;
if(foo === "bar") {}
a << b
var arr = [1, 2];
var c = [];
var baz = [];
a ? b : c
Useless String Concat
Disallows useless string concat.
https://eslint.org/docs/rules/no-useless-concat#no-useless-concat
👍 Examples of correct code
var c = a + b;
var c = '1' + a;
var a = 1 + '1';
var c = 1 - 2;
// when the string concatenation is multiline
var c = "foo" +
"bar";
👎 Examples of incorrect code
var a = `some` + `string`;
// these are the same as "10"
var a = '1' + '0';
var a = '1' + `0`;
var a = `1` + '0';
var a = `1` + `0`;
No Self Assign
Disallows assignments where both sides are exactly the same.
https://eslint.org/docs/rules/no-self-assign#no-self-assign
👍 Examples of correct code
foo = bar;
[a, b] = [b, a];
// This pattern is warned by the `no-use-before-define` rule.
let foo = foo;
// The default values have an effect.
[foo = 1] = [foo];
// non-self-assignments with properties.
obj.a = obj.b;
obj.a.b = obj.c.b;
obj.a.b = obj.a.c;
obj[a] = obj["a"];
👎 Examples of incorrect code
foo = foo;
[a, b] = [a, b];
[a, ...b] = [x, ...b];
({a, b} = {a, x});
foo &&= foo;
foo ||= foo;
foo ??= foo;
Force Return Type
Force fill return type in typescript
👍 Examples of correct code
function test(): void {
return;
}
// A return value of type number
var fn = function (): number {
return 1;
};
// A return value of type string
var arrowFn = (): string => 'test';
class Test {
// No return value should be expected (void)
method(): void {
return;
}
}
👎 Examples of incorrect code
function test() {
return;
}
// Should indicate that a number is returned
var fn = function () {
return 1;
};
// Should indicate that a string is returned
var arrowFn = () => 'test';
class Test {
// Should indicate that no value is returned (void)
method() {
return;
}
}
Array Bracket Line
Requires consistent usage of linebreaks for each pair of brackets. It reports an error if one bracket in the pair has a linebreak inside it and the other bracket does not.
https://eslint.org/docs/rules/array-bracket-newline#consistent
👍 Examples of correct code
var a = [];
var c = [ 1 ];
var d = [
1
];
var f = [
function foo() {
dosomething();
}
];
👎 Examples of incorrect code
var a = [1
];
var b = [
1];
var c = [function foo() {
dosomething();
}
]
var d = [
function foo() {
dosomething();
}]
Unused Vars
Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
https://eslint.org/docs/rules/no-unused-vars#no-unused-vars
👍 Examples of correct code
var x = 10;
alert(x);
// foo is considered used here
myFunc(function foo() {
// ...
}.bind(this));
(function(foo) {
return foo;
})();
var myFunc;
myFunc = setTimeout(function() {
// myFunc is considered used
myFunc();
}, 50);
// Only the second argument from the destructured array is used.
function getY([, y]) {
return y;
}
👎 Examples of incorrect code
// It checks variables you have defined as global
some_unused_var = 42;
var x;
// Write-only variables are not considered as used.
var y = 10;
y = 5;
// A read for a modification of itself is not considered as used.
var z = 0;
z = z + 1;
// By default, unused arguments cause warnings.
(function(foo) {
return 5;
})();
// Unused recursive functions also cause warnings.
function fact(n) {
if (n < 2) return 1;
return n * fact(n - 1);
}
// When a function definition destructures an array, unused entries from the array also cause warnings.
function getY([x, y]) {
return y;
}
Comma Spacing
Putting default parameter at last allows function calls to omit optional tail arguments.
https://eslint.org/docs/rules/comma-spacing#options https://eslint.style/rules/ts/comma-spacing
👍 Examples of correct code
var foo = 1, bar = 2
, baz = 3;
var arr = [1, 2];
var arr = [1,, 3]
var obj = {"foo": "bar", "baz": "qur"};
foo(a, b);
new Foo(a, b);
function foo(a, b){}
a, b
👎 Examples of incorrect code
var foo = 1 ,bar = 2;
var arr = [1 , 2];
var obj = {"foo": "bar" ,"baz": "qur"};
foo(a ,b);
new Foo(a ,b);
function foo(a ,b){}
a ,b
Comma Dangle
This rule enforces consistent use of trailing commas in object and array literals.
https://eslint.org/docs/rules/comma-dangle#comma-dangle https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/comma-dangle.md https://eslint.style/rules/ts/comma-dangle
👍 Examples of correct code
var foo = {
bar: "baz",
qux: "quux",
bar: "baz",
};
function baz(
a,
b,
c,
) {
// code ...
}
👎 Examples of incorrect code
var foo = {
bar: "baz",
qux: "quux",
bar: "baz"
};
function baz(
a,
b,
c
) {
// code ...
}
Arrow Spacing
This rule normalize style of spacing before/after an arrow function’s arrow(=>).
https://eslint.org/docs/latest/rules/arrow-spacing
👍 Examples of correct code
() => {};
(a) => {};
() => {'\n'};
👎 Examples of incorrect code
()=> {};
() =>{};
(a)=> {};
(a) =>{};
a =>a;
a=> a;
()=> {'\n'};
() =>{'\n'};
Prefer Arrow Function
Requires using arrow functions for callbacks.
https://eslint.org/docs/rules/prefer-arrow-callback#prefer-arrow-callback
👍 Examples of correct code
foo(a => a);
foo(() => this.a);
foo(function*() { yield; });
👎 Examples of incorrect code
foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));
Prefer Destructuring
Require destructuring from arrays and/or objects
https://eslint.org/docs/latest/rules/prefer-destructuring https://sonarsource.github.io/rspec/#/rspec/S3514/javascript
👍 Examples of correct code
var [ foo ] = array;
var foo = array[someIndex];
var { foo } = object;
var foo = object.bar;
let foo;
({ foo } = object);
👎 Examples of incorrect code
// With `array` enabled
var foo = array[0];
// With `object` enabled
var foo = object.foo;
var foo = object['foo'];
Arrow Function Body
Enforces no braces where they can be omitted
https://eslint.org/docs/rules/arrow-body-style#arrow-body-style
👍 Examples of correct code
() => {};
(a) => {};
(a) => a;
(a) => {'\n'}
a.then((foo) => {});
a.then((foo) => { if (true) {} });
👎 Examples of incorrect code
a => {};
a => a;
a => {'\n'};
a.then(foo => {});
a.then(foo => a);
a(foo => { if (true) {} });
Arrow Function Parentheses
Enforces parentheses around arguments in all cases.
https://eslint.org/docs/rules/arrow-parens
👍 Examples of correct code
let foo = () => 0;
let foo = (retv, name) => {
retv[name] = true;
return retv;
};
let foo = () => ({
bar: {
foo: 1,
bar: 2,
}
});
let foo = () => { bar(); };
let foo = () => {};
let foo = () => { /* do nothing */ };
let foo = () => {
// do nothing.
};
let foo = () => ({ bar: 0 });
👎 Examples of incorrect code
let foo = () => {
return 0;
};
let foo = () => {
return {
bar: {
foo: 1,
bar: 2,
}
};
};
Arrow Function No Break Line
Enforces parentheses around arguments in all cases.
https://eslint.org/docs/rules/arrow-parens
👍 Examples of correct code
(foo) => bar;
(foo) => (bar);
(foo) => bar => baz;
(foo) => (
bar()
);
// functions with block bodies allowed with this rule using any style
// to enforce a consistent location for this case, see the rule: `brace-style`
(foo) => {
return bar();
}
(foo) =>
{
return bar();
}
👎 Examples of incorrect code
(foo) =>
bar;
(foo) =>
(bar);
(foo) =>
bar =>
baz;
(foo) =>
(
bar()
);
No Empty Block
Disallows empty block statements.
https://eslint.org/docs/rules/no-empty#no-empty
👍 Examples of correct code
if (!foo) {
// code
}
while (foo) {
// code
}
try {
doSomething();
} catch (ex) {
// continue regardless of error
}
try {
doSomething();
} finally {
/* continue regardless of error */
}
👎 Examples of incorrect code
if (foo) {
} else {
// code
}
while (foo) {
}
switch(foo) {
}
try {
doSomething();
} catch(ex) {
} finally {
}
No Long Syntax
Disallow Array constructors
https://eslint.org/docs/latest/rules/no-array-constructor
👍 Examples of correct code
const arr: Array<number> = [ 1, 2, 3 ];
const arr: Array<Foo> = [ x, y, z ];
Array(500);
new Array(someOtherArray.length);
👎 Examples of incorrect code
const arr = Array(0, 1, 2);
const arr = new Array(0, 1, 2);
Useless Parens
Disallows unnecessary parentheses.
https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-extra-parens.md https://eslint.org/docs/rules/no-extra-parens#no-extra-parens https://eslint.style/rules/ts/no-extra-parens
👍 Examples of correct code
a = (b * c);
(a * b) + c;
for (a in (b, c));
for (a in (b));
for (a of (b));
typeof (a);
(function(){} ? a() : b());
class A {
[(x)] = 1;
}
class B {
x = (y + z);
}
👎 Examples of incorrect code
a = (b * c);
(a * b) + c;
for (a in (b, c));
for (a in (b));
for (a of (b));
typeof (a);
(function(){} ? a() : b());
class A {
[(x)] = 1;
}
class B {
x = (y + z);
}
Useless Boolean
Disallow useless code
https://eslint.org/docs/rules/no-useless-constructor#options
👍 Examples of correct code
var foo = !!bar;
var foo = Boolean(bar);
function foo() {
return !!bar;
}
var foo = bar ? !!baz : !!bat;
👎 Examples of incorrect code
var foo = !!!bar;
var foo = !!bar ? baz : bat;
var foo = Boolean(!!bar);
var foo = new Boolean(!!bar);
if (!!foo) {
// ...
}
if (Boolean(foo)) {
// ...
}
while (!!foo) {
// ...
}
do {
// ...
} while (Boolean(foo));
for ( ;!!foo; ) {
// ...
}
Useless Alias
Disallows renaming import, export, and destructured assignments to the same name.
https://eslint.org/docs/rules/no-useless-rename
👍 Examples of correct code
import * as foo from "foo";
import { foo } from "bar";
import { foo as bar } from "baz";
import { "foo" as bar } from "baz";
export { foo };
export { foo as bar };
export { foo as bar } from "foo";
let { foo } = bar;
let { foo: bar } = baz;
let { [foo]: foo } = bar;
function foo({ bar }) {}
function foo({ bar: baz }) {}
({ foo }) => {}
({ foo: bar }) => {}
👎 Examples of incorrect code
import { foo as foo } from "bar";
import { "foo" as foo } from "bar";
export { foo as foo };
export { foo as "foo" };
export { foo as foo } from "bar";
export { "foo" as "foo" } from "bar";
let { foo: foo } = bar;
let { 'foo': foo } = bar;
function foo({ bar: bar }) {}
({ foo: foo }) => {}
Return New line
Force new line before return
https://eslint.org/docs/rules/newline-before-return#newline-before-return
👍 Examples of correct code
function foo(bar) {
var baz = 'baz';
if (bar()) {
return true;
}
if (!bar) {
bar = baz;
return baz;
}
return bar;
}
👎 Examples of incorrect code
function foo(bar) {
var baz = 'baz';
if (bar()) {
return true;
}
if (!bar) {
bar = baz;
return bar;
}
return bar;
}
Comment Multi Line Prefer
Prefer Multi-line comment formated
https://eslint.org/docs/rules/newline-before-return#newline-before-return
👍 Examples of correct code
/*
* this line
* calls foo()
*/
foo();
// single-line comment
👎 Examples of incorrect code
// this line
// calls foo()
foo();
/* this line
calls foo() */
foo();
/* this comment
* is missing a newline after /*
*/
/*
* this comment
* is missing a newline at the end */
/*
* the star in this line should have a space before it
*/
/*
* the star on the following line should have a space before it
*/
No throw Literal
Create custom class to Throw
https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-throw-literal.md https://eslint.org/docs/rules/prefer-promise-reject-errors#prefer-promise-reject-errors
👍 Examples of correct code
class CustomError extends Error {
// ...
};
const e = new CustomError("error");
throw e;
throw new CustomError("error");
function err() {
return new CustomError();
}
throw err();
const foo = {
bar: new CustomError();
}
throw foo.bar;
// promises
Promise.reject(new CustomError("something bad happened"));
Promise.reject(new TypeError("something bad happened"));
new Promise(function(resolve, reject) {
reject(new CustomError("something bad happened"));
});
var foo = getUnknownValue();
Promise.reject(foo);
👎 Examples of incorrect code
throw new Error();
throw 'error';
throw 0;
throw undefined;
throw null;
const err = new Error();
throw 'an ' + err;
const err = new Error();
throw `${err}`;
const err = '';
throw err;
function err() {
return '';
}
throw err();
const foo = {
bar: '',
};
throw foo.bar;
// Promise
Promise.reject("something bad happened");
Promise.reject(5);
Promise.reject();
new Promise(function(resolve, reject) {
reject("something bad happened");
});
new Promise(function(resolve, reject) {
reject();
});
No Unreachable
No Unreachable code
https://eslint.org/docs/rules/no-unreachable https://sonarsource.github.io/rspec/#/rspec/S6079/javascript
👍 Examples of correct code
function foo() {
function bar() {
return 1;
}
return bar();
}
function bar() {
var x;
return x;
}
switch (foo) {
case 1:
break;
}
👎 Examples of incorrect code
function foo() {
return true;
console.log("done");
}
function bar() {
throw new Error("Oops!");
console.log("done");
}
while(value) {
break;
console.log("done");
}
throw new Error("Oops!");
console.log("done");
function baz() {
if (Math.random() < 0.5) {
return;
} else {
throw new Error();
}
console.log("done");
}
for (;;) {}
console.log("done");
No Multiline String
Prevent break line in string
https://eslint.org/docs/rules/no-multi-str#no-multi-str
👍 Examples of correct code
var x = "some very\nlong text";
var x = "some very " +
"long text";
👎 Examples of incorrect code
var x = "some very \
long text";
No Unsafe Assign
Disallows assigning any to variables and properties.
👍 Examples of correct code
const x = 1,
y = 1;
const [x] = [1];
[x] = [1] as [number];
function foo(a = 1) {}
class Foo {
constructor(private a = 1) {}
}
class Foo {
private a = 1;
}
// generic position examples
const x: Set<string> = new Set<string>();
const x: Map<string, string> = new Map<string, string>();
const x: Set<string[]> = new Set<string[]>();
const x: Set<Set<Set<string>>> = new Set<Set<Set<string>>>();
👎 Examples of incorrect code
const x = 1 as any,
y = 1 as any;
const [x] = 1 as any;
const [x] = [] as any[];
const [x] = [1 as any];
[x] = [1] as [any];
function foo(a = 1 as any) {}
class Foo {
constructor(private a = 1 as any) {}
}
class Foo {
private a = 1 as any;
}
// generic position examples
const x: Set<string> = new Set<any>();
const x: Map<string, string> = new Map<string, any>();
const x: Set<string[]> = new Set<any[]>();
const x: Set<Set<Set<string>>> = new Set<Set<Set<any>>>();
Disallow Script Url
Using javascript: URLs is considered by some as a form of eval.
https://eslint.org/docs/rules/no-script-url
👍 Examples of correct code
location.href = "#";
👎 Examples of incorrect code
location.href = "javascript:void(0)";
location.href = `javascript:void(0)`;
Disallow Undefined
Disallows the use of undeclared variables unless mentioned in /*global*/ comments.
https://eslint.org/docs/rules/no-undef
👍 Examples of correct code
/* global someFunction, a */
var foo = someFunction();
var bar = a + 1;
👎 Examples of incorrect code
var foo = someFunction();
var bar = a + 1;
Function Name
Requires function expressions to have a name, if the name isn't assigned automatically per the ECMAScript specification.
https://eslint.org/docs/rules/func-names https://sonarsource.github.io/rspec/#/rspec/S100/javascript
👍 Examples of correct code
/* global someFunction, a */
var foo = someFunction();
var bar = a + 1;
👎 Examples of incorrect code
Foo.prototype.bar = function() {};
(function() {
// ...
}())
export default function() {}
Function Name Match
This rule requires function names to match the name of the variable or property to which they are assigned. The rule will ignore property assignments where the property name is a literal that is not a valid identifier in the ECMAScript version specified in your configuration (default ES5).
https://eslint.org/docs/latest/rules/func-name-matching
👍 Examples of correct code
var foo = function foo() {};
var foo = function() {};
var foo = () => {};
foo = function foo() {};
obj.foo = function foo() {};
obj['foo'] = function foo() {};
obj['foo//bar'] = function foo() {};
obj[foo] = function bar() {};
var obj = {foo: function foo() {}};
var obj = {[foo]: function bar() {}};
var obj = {'foo//bar': function foo() {}};
var obj = {foo: function() {}};
obj['x' + 2] = function bar(){};
var [ bar ] = [ function bar(){} ];
({[foo]: function bar() {}})
class C {
foo = function foo() {};
baz = function() {};
}
// private names are ignored
class D {
#foo = function foo() {};
#bar = function foo() {};
baz() {
this.#foo = function foo() {};
this.#foo = function bar() {};
}
}
module.exports = function foo(name) {};
module['exports'] = function foo(name) {};
👎 Examples of incorrect code
var foo = function bar() {};
foo = function bar() {};
obj.foo = function bar() {};
obj['foo'] = function bar() {};
var obj = {foo: function bar() {}};
({['foo']: function bar() {}});
class C {
foo = function bar() {};
}
No Use Future Reserved Words
"future reserved words" should not be used as identifiers Special identifiers should not be bound or assigned
https://sonarsource.github.io/rspec/#/rspec/S2137/javascript
👍 Examples of correct code
var elements = document.getElementsByName("foo"); // Compliant
var someData = { package: true };
result = 17;
++result;
var obj = { set p(arg) { } };
var result;
try { } catch (args) { }
function x(arg) { }
function args() { }
var y = function fun() { };
var f = new Function("args", "return 17;");
👎 Examples of incorrect code
var package = document.getElementsByName("foo"); // Noncompliant
eval = 17; // Noncompliant
arguments++; // Noncompliant
++eval; // Noncompliant
var obj = { set p(arguments) { } }; // Noncompliant
var eval; // Noncompliant
try { } catch (arguments) { } // Noncompliant
function x(eval) { } // Noncompliant
function arguments() { } // Noncompliant
var y = function eval() { }; // Noncompliant
var f = new Function("arguments", "return 17;"); // Noncompliant
No Generator Without Yield
Generators should "yield" something
https://sonarsource.github.io/rspec/#/rspec/S3531/javascript
👍 Examples of correct code
function* myGen(a, b) {
let answer = 0;
while (answer < 42) {
answer += a * b;
yield answer;
}
}
👎 Examples of incorrect code
function* myGen(a, b) { // Noncompliant
let answer = 0;
answer += a * b;
}
Inverted Assertion Arguments
Assertion arguments should be passed in the correct order
https://sonarsource.github.io/rspec/#/rspec/S3415/javascript
👍 Examples of correct code
const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();
it("inverts arguments", function() {
assert.equal(aNumber, 42);
expect(aNumber).to.equal(42);
should.fail(aNumber, 42);
});
👎 Examples of incorrect code
const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();
it("inverts arguments", function() {
assert.equal(42, aNumber); // Noncompliant
expect(42).to.equal(aNumber); // Noncompliant
should.fail(42, aNumber); // Noncompliant
});
Max Union Size
Union types should not have too many elements
https://sonarsource.github.io/rspec/#/rspec/S4622/javascript
👍 Examples of correct code
type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; // Compliant, "type" statements are ignored
let x: MyUnionType;
function foo(value: string, padding: MyUnionType) {
// ...
}
👎 Examples of incorrect code
let x: MyType1 | MyType2 | MyType3 | MyType4; // Noncompliant
function foo(p1: string, p2: MyType1 | MyType2 | MyType3 | MyType4) { // Noncompliant
// ...
}
No Redundant Optional
Optional property declarations should not use both '?' and 'undefined' syntax
https://sonarsource.github.io/rspec/#/rspec/S4782/javascript
👍 Examples of correct code
interface Person {
name: string;
address: string | undefined;
pet?: Animal;
}
👎 Examples of incorrect code
interface Person {
name: string;
address? : string | undefined; // Noncompliant, "?" should be removed
pet?: Animal | undefined; // Noncompliant, "undefined" should be removed
}
Prefer Type Guard
Type guards should be used
https://sonarsource.github.io/rspec/#/rspec/S4322/javascript
👍 Examples of correct code
function isSomething(x: BaseType) : x is Something {
return (<Something>x).foo !== undefined;
}
if (isSomething(v)) {
v.foo();
}
👎 Examples of incorrect code
function isSomething(x: BaseType) : boolean { // Noncompliant
return (<Something>x).foo !== undefined;
}
if (isSomething(v)) {
(<Something>v).foo();
}
No Production Debug
Delivering code in production with debug features activated is security-sensitive
https://sonarsource.github.io/rspec/#/rspec/S4507/javascript
👍 Examples of correct code
const express = require('express');
const errorhandler = require('errorhandler');
let app = express();
if (process.env.NODE_ENV === 'development') { // Compliant
app.use(errorhandler()); // Compliant
}
👎 Examples of incorrect code
const express = require('express');
const errorhandler = require('errorhandler');
let app = express();
app.use(errorhandler()); // Sensitive
Unused Named Groups
Why use named groups only to never use any of them later on in the code?
This rule raises issues every time named groups are: defined but never called anywhere in the code through their name; defined but called elsewhere in the code by their number instead; referenced while not defined.
https://sonarsource.github.io/rspec/#/rspec/S5860/javascript
👍 Examples of correct code
const date = "01/02";
const datePattern = /(?<month>[0-9]{2})\/(?<year>[0-9]{2})/;
const dateMatched = date.match(datePattern);
if (dateMatched !== null) {
checkValidity(dateMatched.groups.month, dateMatched.groups.year);
}
// ...
const score = "14:1";
const scorePattern = /(?<player1>[0-9]+):(?<player2>[0-9]+)/;
const scoreMatched = score.match(scorePattern);
if (scoreMatched !== null) {
checkScore(scoreMatched.groups.player1);
checkScore(scoreMatched.groups.player2);
}
👎 Examples of incorrect code
const date = "01/02";
const datePattern = /(?<month>[0-9]{2})\/(?<year>[0-9]{2})/;
const dateMatched = date.match(datePattern);
if (dateMatched !== null) {
checkValidity(dateMatched[1], dateMatched[2]); // Noncompliant - numbers instead of names of groups are used
checkValidity(dateMatched.groups.day); // Noncompliant - there is no group called "day"
}
// ...
const score = "14:1";
const scorePattern = /(?<player1>[0-9]+):(?<player2>[0-9]+)/; // Noncompliant - named groups are never used
const scoreMatched = score.match(scorePattern);
if (scoreMatched !== null) {
checkScore(score);
}
Get And Setters
A getter and setter for the same property don’t necessarily have to be defined adjacent to each other.
https://eslint.org/docs/latest/rules/grouped-accessor-pairs
👍 Examples of correct code
var foo = {
get a() {
return this.val;
},
set a(value) {
this.val = value;
},
b: 1
};
var bar = {
set b(value) {
this.val = value;
},
get b() {
return this.val;
},
a: 1
}
class Foo {
set a(value) {
this.val = value;
}
get a() {
return this.val;
}
b(){}
}
const Bar = class {
static get a() {
return this.val;
}
static set a(value) {
this.val = value;
}
}
👎 Examples of incorrect code
var foo = {
get a() {
return this.val;
},
b: 1,
set a(value) {
this.val = value;
}
};
var bar = {
set b(value) {
this.val = value;
},
a: 1,
get b() {
return this.val;
}
}
class Foo {
set a(value) {
this.val = value;
}
b(){}
get a() {
return this.val;
}
}
const Bar = class {
static get a() {
return this.val;
}
b(){}
static set a(value) {
this.val = value;
}
}
Function Style
Enforce the consistent use of either function declarations or expressions
https://eslint.org/docs/latest/rules/func-style
👍 Examples of correct code
function foo() {
// ...
}
// Methods (functions assigned to objects) are not checked by this rule
SomeObject.foo = function() {
// ...
};
👎 Examples of incorrect code
var foo = function() {
// ...
};
var foo = () => {};
No Else Return
Disallow else blocks after return statements in if statements
https://eslint.org/docs/latest/rules/no-else-return
👍 Examples of correct code
function foo() {
if (x) {
return y;
}
return z;
}
function foo() {
if (x) {
return y;
} else if (z) {
var t = "foo";
} else {
return w;
}
}
function foo() {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}
function foo() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
👎 Examples of incorrect code
function foo() {
if (x) {
return y;
} else {
return z;
}
}
function foo() {
if (x) {
return y;
} else if (z) {
return w;
} else {
return t;
}
}
function foo() {
if (x) {
return y;
} else {
var t = "foo";
}
return t;
}
function foo() {
if (error) {
return 'It failed';
} else {
if (loading) {
return "It's still loading";
}
}
}
// Two warnings for nested occurrences
function foo() {
if (x) {
if (y) {
return y;
} else {
return x;
}
} else {
return z;
}
}
No Console Spaces
The console.log() method and similar methods joins the parameters with a space, so adding a leading/trailing space to a parameter, results in two spaces being added.
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-console-spaces.md
👍 Examples of correct code
console.log('abc');
console.log('abc', 'def');
console.log('abc ');
console.log(' abc');
console.log('abc ', 'def');
console.log('abc\t', 'def');
console.log('abc\n', 'def');
console.log(`
abc
`);
👎 Examples of incorrect code
console.log('abc ', 'def');
console.log('abc', ' def');
console.log("abc ", " def");
console.log(`abc `, ` def`);
console.debug('abc ', 'def');
console.info('abc ', 'def');
console.warn('abc