Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only arrow functions in eslint?

I prefer this:

const foo = x => x + 1;

to this:

function foo(x) {
  return x + 1;
}

Is there an eslint rule to enforce this?

like image 208
sdgfsdh Avatar asked Oct 05 '18 15:10

sdgfsdh


2 Answers

You can use this ESLint prefer-arrow-callback rule which would flag with error/warning anywhere you could use an arrow function instead of a function expression

like image 154
Kevin Amiranoff Avatar answered Nov 15 '22 21:11

Kevin Amiranoff


Anser based on @JohannesEwald comment and @KevinAmiranoff answer.

I'm using the following rules:

https://www.npmjs.com/package/eslint-plugin-prefer-arrow

https://eslint.org/docs/rules/prefer-arrow-callback

https://eslint.org/docs/rules/func-style

npm install -D eslint-plugin-prefer-arrow

.eslintrc or package.json with eslintConfig:

"plugins": [
  "prefer-arrow"
],
"rules": {
  "prefer-arrow/prefer-arrow-functions": [
    "error",
    {
      "disallowPrototype": true,
      "singleReturnOnly": false,
      "classPropertiesAllowed": false
    }
  ],
  "prefer-arrow-callback": [
    "error",
    { "allowNamedFunctions": true }
  ],
  "func-style": [
    "error",
    "expression",
    { "allowArrowFunctions": true }
  ]
}

I think this works really well. If you need to disable the rules for a specific line I do it like this:

// eslint-disable-next-line func-style, prefer-arrow/prefer-arrow-functions
like image 42
Ogglas Avatar answered Nov 15 '22 22:11

Ogglas