0.8.0 β€’ Published 2 years ago

@odg/eslint-config-odg-linter-js v0.8.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Standard Code

Introduction

Installation

Add dependence to package.json

npm install eslint @odg/eslint-config-odg-linter-js \
    eslint-plugin-jsdoc@* eslint-plugin-import@* \
    eslint-plugin-promise@* eslint-plugin-regexp@* \
    eslint-plugin-filenames@* --save-dev
# or
yarn add -D eslint @odg/eslint-config-odg-linter-js \
    eslint-plugin-jsdoc@* eslint-plugin-import@* \
    eslint-plugin-promise@* eslint-plugin-regexp@* \
    eslint-plugin-filenames@*

Add extends in your .eslintrc file

{
    "extends": [
        "@odg/odg-linter-js",
    ],
    "overrides": [
        {
            "files": [ "*.ts", "*.tsx" ],
            "parser": "@typescript-eslint/parser",
            "parserOptions": {
                "ecmaFeatures": { "jsx": true },
                "ecmaVersion": 2018,
                "sourceType": "module",
                "project": [ "tsconfig.json" ], // Specify it only for TypeScript files
            },
        },
    ],
}

Test: npm run eslint or yarn eslint

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

πŸ‘ Examples of correct code

var name = "ODG";

object.method = function() {
    // ...
};

class Foo {
    bar = 1;
}

πŸ‘Ž Examples of incorrect code

var name = "ODG"

object.method = function() {
    // ...
}

class Foo {
    bar = 1
}

Quotes Rule


Requires the use of double quotes wherever possible

https://eslint.org/docs/rules/quotes#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

https://eslint.org/docs/rules/indent#indent https://sonarsource.github.io/rspec/#/rspec/S3973/javascript

πŸ‘ 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" };

CamelCase Rule


Force use camelcase 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() {
    // ...
}

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

πŸ‘ 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

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md

{
    "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://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/space-before-function-paren.md

πŸ‘ 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

πŸ‘ Examples of correct code

if (foo) {
    //...
} else if (bar) {
    //...
} else {
    //...
}

try {

} catch(e) {
    // code ...
}

πŸ‘Ž Examples of incorrect code

if(foo){
    //...
}else if(bar){
    //...
}else{
    //...
}

try{

}catch(e){
    // code ...
}

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

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-function-return-type.md

πŸ‘ 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

πŸ‘ 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

πŸ‘ 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 ...
}

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

πŸ‘ 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,
        }
    };
};

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 Call Code


Disallow useless code

https://eslint.org/docs/rules/no-useless-call#no-useless-call

πŸ‘ Examples of correct code

foo.call(obj, 1, 2, 3);
foo.apply(obj, [1, 2, 3]);
obj.foo.call(null, 1, 2, 3);
obj.foo.apply(null, [1, 2, 3]);
obj.foo.call(otherObj, 1, 2, 3);
obj.foo.apply(otherObj, [1, 2, 3]);

// The argument list is variadic.
// Those are warned by the `prefer-spread` rule.
foo.apply(undefined, args);
foo.apply(null, args);
obj.foo.apply(obj, args);

a[++i].foo.call(a[i], 1, 2, 3);

πŸ‘Ž Examples of incorrect code

foo.call(undefined, 1, 2, 3);
foo.apply(undefined, [1, 2, 3]);
foo.call(null, 1, 2, 3);
foo.apply(null, [1, 2, 3]);

// These are same as `obj.foo(1, 2, 3);`
obj.foo.call(obj, 1, 2, 3);
obj.foo.apply(obj, [1, 2, 3]);

a[i++].foo.call(a[i++], 1, 2, 3);

Useless Catch Code


Disallow useless code

https://eslint.org/docs/rules/no-useless-catch#no-useless-catch

πŸ‘ Examples of correct code

try {
  doSomethingThatMightThrow();
} catch (e) {
  doSomethingBeforeRethrow();
  throw e;
}

try {
  doSomethingThatMightThrow();
} catch (e) {
  handleError(e);
}

try {
  doSomethingThatMightThrow();
} finally {
  cleanUp();
}

πŸ‘Ž Examples of incorrect code

try {
  doSomethingThatMightThrow();
} catch (e) {
  throw e;
}

try {
  doSomethingThatMightThrow();
} catch (e) {
  throw e;
} finally {
  cleanUp();
}

Useless Expression Code


Disallow useless code

https://eslint.org/docs/rules/no-unused-expressions

πŸ‘ Examples of correct code

{} // In this context, this is a block statement, not an object literal

{myLabel: someVar} // In this context, this is a block statement with a label and expression, not an object literal

function namedFunctionDeclaration () {}

(function aGenuineIIFE () {}());

f()

a = 0

new C

delete a.b

void a

a ? b() : c();
a ? (b = c) : d();

πŸ‘Ž Examples of incorrect code

0

if(0) 0

{0}

f(0), {}

a && b()

a, b()

c = a, b;

a() && function namedFunctionInExpressionContext () {f();}

(function anIncompleteIIFE () {});

injectGlobal`body{ color: red; }`

function foo() {
    "bar" + 1;
}

class Foo {
    static {
        "use strict"; // class static blocks do not have directive prologues
    }
}

Useless Return Code


Disallow useless code

https://eslint.org/docs/rules/no-useless-return#no-useless-return

πŸ‘ Examples of correct code

function foo() { return 5; }

function foo() {
  return doSomething();
}

function foo() {
  if (condition) {
    bar();
    return;
  } else {
    baz();
  }
  qux();
}

function foo() {
  switch (bar) {
    case 1:
      doSomething();
      return;
    default:
      doSomethingElse();
  }
}

function foo() {
  for (const foo of bar) {
    return;
  }
}

πŸ‘Ž Examples of incorrect code

function foo() { return; }

function foo() {
  doSomething();
  return;
}

function foo() {
  if (condition) {
    bar();
    return;
  } else {
    baz();
  }
}

function foo() {
  switch (bar) {
    case 1:
      doSomething();
    default:
      doSomethingElse();
      return;
  }
}

Useless Construct Code


Disallow useless code

https://eslint.org/docs/rules/no-useless-constructor#options

πŸ‘ Examples of correct code

class A { }

class A {
    constructor () {
        doSomething();
    }
}

class B extends A {
    constructor() {
        super('foo');
    }
}

class B extends A {
    constructor() {
        super();
        doSomething();
    }
}

πŸ‘Ž Examples of incorrect code

class A {
    constructor () {
    }
}

class B extends A {
    constructor (...args) {
      super(...args);
    }
}

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

πŸ‘ 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

πŸ‘ 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.

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md

πŸ‘ 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

πŸ‘ 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 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 ', 'def');
console.error('abc ', 'def');

No Hex Escape


Enforce the use of Unicode escapes instead of hexadecimal escapes

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-hex-escape.md

πŸ‘ Examples of correct code

const foo = '\u001B';
const foo = `\u001B${bar}`;

πŸ‘Ž Examples of incorrect code

const foo = '\x1B';
const foo = `\x1B${bar}`;

Prefer Array Flat Map


Prefer .flatMap(…) over .map(…).flat()

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-array-flat-map.md

πŸ‘ Examples of correct code

const foo = bar.flatMap(element => unicorn(element));
const foo = bar.map(element => unicorn(element)).flat(2);
const foo = bar.map(element => unicorn(element)).foo().flat();
const foo = bar.flat().map(element => unicorn(element));

πŸ‘Ž Examples of incorrect code

const foo = bar.map(element => unicorn(element)).flat();
const foo = bar.map(element => unicorn(element)).flat(1);

Prefer String Slice


Prefer String#slice() over String#substr() and String#substring()

String#substr() and String#substring() are the two lesser known legacy ways to slice a string. It's better to use String#slice() as it's a more popular option with clearer behavior that has a consistent Array counterpart.

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-string-slice.md

πŸ‘ Examples of correct code

foo.slice(beginIndex, endIndex);

πŸ‘Ž Examples of incorrect code

foo.substr(start, length);
foo.substring(indexStart, indexEnd);

Prefer Modern DOM


Prefer .before() over .insertBefore(), .replaceWith() over .replaceChild(), prefer one of .before(), .after(), .append() or .prepend() over insertAdjacentText() and insertAdjacentElement()

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-modern-dom-apis.md

πŸ‘ Examples of correct code

foo.replaceWith(bar);
foo.replaceWith('bar');
foo.replaceWith(bar, 'baz'));

foo.before(bar)
foo.before('bar')
foo.before(bar, 'baz')

foo.prepend(bar)
foo.prepend('bar')
foo.prepend(bar, 'baz')

foo.append(bar)
foo.append('bar')
foo.append(bar, 'baz')

foo.after(bar)
foo.after('bar')
foo.after(bar, 'baz')

πŸ‘Ž Examples of incorrect code

foo.replaceChild(baz, bar);

foo.insertBefore(baz, bar);

foo.insertAdjacentText('position', bar);

foo.insertAdjacentElement('position', bar);

Prefer Prefix Number


Prefer Number static properties over global ones

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-number-properties.md

πŸ‘ Examples of correct code

const foo = Number.parseInt('10', 2);

const foo = Number.parseFloat('10.5');

const foo = Number.isNaN(10);

const foo = Number.isFinite(10);

if (Object.is(foo, Number.NaN)) {}

const isPositiveZero = value => value === 0 && 1 / value === Number.POSITIVE_INFINITY;

const isNegativeZero = value => value === 0 && 1 / value === Number.NEGATIVE_INFINITY;

πŸ‘Ž Examples of incorrect code

const foo = parseInt('10', 2);

const foo = parseFloat('10.5');

const foo = isNaN(10);

const foo = isFinite(10);

if (Object.is(foo, NaN)) {}

const isPositiveZero = value => value === 0 && 1 / value === Infinity;

const isNegativeZero = value => value === 0 && 1 / value === -Infinity;

const {parseInt} = Number;
const foo = parseInt('10', 2);

Numeric Separators Style


Enforce the style of numeric separators by correctly grouping digits

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/numeric-separators-style.md

πŸ‘ Examples of correct code

const foo = 1_234_444;
const foo = 1_234.567_89;
const foo = 0xAB_CD_EF;
const foo = 0b1000_1111;
const foo = 0o10_4421;
const foo = 1_294_287_712n;

πŸ‘Ž Examples of incorrect code

const foo = 1_23_4444;
const foo = 1_234.56789;
const foo = 0xAB_C_D_EF;
const foo = 0b10_00_1111;
const foo = 0o1_0_44_21;
const foo = 1_294_28771_2n;

Prefer Default Parame


Prefer default parameters over reassignment

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-default-parameters.md

πŸ‘ Examples of correct code

function abc(foo = 'bar') {}
function abc(foo) {
    const parameter = foo || bar();
}

πŸ‘Ž Examples of incorrect code

function abc(foo) {
    foo = foo || 'bar';
}
function abc(foo) {
    const bar = foo || 'bar';
}

No Avoid Reverse


Prefer Array#flat() over legacy techniques to flatten arrays

https://github.com/freaktechnik/eslint-plugin-array-func#avoid-reverse

πŸ‘ Examples of correct code

const string = array.reduceRight((p, c) => p + c, "");

const reverseString = array.reduce((p, c) => p + c, "");

πŸ‘Ž Examples of incorrect code

const string = array.reverse().reduce((p, c) => p + c, '');

const reverseString = array.reverse().reduceRight((p, c) => p + c, '');

Bool Param Default


Optional boolean parameters should have default value

https://sonarsource.github.io/rspec/#/rspec/S4798/javascript

πŸ‘ Examples of correct code

function countPositiveNumbers(arr: number[], countZero = false) {
  // ...
}

function toggleProperty(property: string, value: boolean) {
  setProperty(property, value);
}

function togglePropertyToCalculatedValue(property: string) {
  setProperty(property, calculateProperty());
}

πŸ‘Ž Examples of incorrect code

function countPositiveNumbers(arr: number[], countZero?: boolean) { // Noncompliant, default value for 'countZero' should be defined
  // ...
}

function toggleProperty(property: string, value?: boolean) { // Noncompliant, a new function should be defined
  if (value !== undefined) {
    setProperty(property, value);
  } else {
    setProperty(property, calculateProperty());
  }
}

Class Name Convention


Class names should comply with a naming convention

https://sonarsource.github.io/rspec/#/rspec/S101/javascript

πŸ‘ Examples of correct code

// With default provided regular expression /^[A-Z][a-zA-Z0-9]*$/:
class MyClass { }

πŸ‘Ž Examples of incorrect code

class my_class { }

No Class prototype


Class methods should be used instead of "prototype" assignments

https://sonarsource.github.io/rspec/#/rspec/S3525/javascript

πŸ‘ Examples of correct code

class MyClass {
  constructor(initializerArgs = []) {
    this._values = [...initializerArgs];
  }

  doSomething() {
    //...
  }
}

πŸ‘Ž Examples of incorrect code

function MyNonClass(initializerArgs = []) {
  this._values = [...initializerArgs];
}

MyNonClass.prototype.doSomething = function () {  // Noncompliant
  // ...
}

Comma Or Logical Or Case


Comma and logical OR operators should not be used in switch cases

https://sonarsource.github.io/rspec/#/rspec/S3616/javascript

πŸ‘ Examples of correct code

switch (a) {
  case 1:
  case 2:
    doTheThing(a);
  case 3:
  case 4:
    doThatThing(a);
  case 5:
    doTheOtherThing(a);
  default:
    console.log('Neener, neener!');
}

πŸ‘Ž Examples of incorrect code

switch (a) {
  case 1,2:  // Noncompliant; only 2 is ever handled by this case
    doTheThing(a);
  case 3 || 4: // Noncompliant; only '3' is handled
    doThatThing(a);
  case 5:
    doTheOtherThing(a);
  default:
    console.log('Neener, neener!');  // this happens when a==1 or a == 4
}

No Constructor Bind


Prefer class properties to equivalent setup steps taken in a class' constructor method.

https://github.com/markalfred/eslint-plugin-no-constructor-bind

πŸ‘ Examples of correct code

class User {
  greet = () => 'hello'
}

πŸ‘Ž Examples of incorrect code

class User {
  constructor() {
    this.greet = this.greet.bind(this)
  }
  greet() { return 'Hello' }
}

Prefer Code Point


Prefer String#codePointAt(…) over String#charCodeAt(…) and String.fromCodePoint(…) over String.fromCharCode(…)

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-code-point.md

πŸ‘ Examples of correct code

const unicorn = 'πŸ¦„'.codePointAt(0).toString(16);
const unicorn = String.fromCodePoint(0x1f984);

πŸ‘Ž Examples of incorrect code

const unicorn = 'πŸ¦„'.charCodeAt(0).toString(16);
const unicorn = String.fromCharCode(0x1f984);

No Thenable


If an object is defined as "thenable", once it's accidentally used in an await expression, it may cause problems:

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-thenable.md

πŸ‘ Examples of correct code

export {then as success};
const foo = {
    success() {}
};
class Foo {
    success() {}
}
const foo = bar.then;

πŸ‘Ž Examples of incorrect code

export {then};
const foo = {
    then() {}
};
const foo = {
    get then() {}
};
foo.then = function () {}
class Foo {
    then() {}
}
class Foo {
    static then() {}
}

No Unreadable Iife


IIFE with parenthesized arrow function body is considered unreadable.

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-unreadable-iife.md

πŸ‘ Examples of correct code

const bar = getBar();
const foo = bar ? bar.baz : baz;

const getBaz = bar => (bar ? bar.baz : baz);
const foo = getBaz(getBar());

const foo = (bar => {
    return bar ? bar.baz : baz;
})(getBar());

πŸ‘Ž Examples of incorrect code

const foo = (bar => (bar ? bar.baz : baz))(getBar());
const foo = ((bar, baz) => ({bar, baz}))(bar, baz);

Prefer Native Cast


Prefer using String, Number, BigInt, Boolean, and Symbol directly

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-native-coercion-functions.md

πŸ‘ Examples of correct code

const toBoolean = Boolean;

if (Number(foo) === 1) {}

const hasTruthyValue = array.some(Boolean);

const toStringObject = value => new String(value);

const toObject = value => Object(value);

πŸ‘Ž Examples of incorrect code

const toBoolean = value => Boolean(value);
function toNumber(value) {
    return Number(value);
}

if (toNumber(foo) === 1) {}
const hasTruthyValue = array.some(element => element);

Prefer Logical Operator Over Ternary


Prefer using a logical operator over a ternary

Ideally, most reported cases have an equivalent Logical OR(||) expression. The rule intentionally provides suggestions instead of auto-fixes, because in many cases, the nullish coalescing operator (??) should be preferred.

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-logical-operator-over-ternary.md

πŸ‘ Examples of correct code

foo ?? bar;
foo || bar;
foo ? bar : baz;
foo.bar ?? foo.baz
foo?.bar ?? baz

πŸ‘Ž Examples of incorrect code

foo