Giter Site home page Giter Site logo

htmlacademy / eslint-config-htmlacademy Goto Github PK

View Code? Open in Web Editor NEW
40.0 9.0 23.0 333 KB

ESLint rules that uses on all HTML Academy professional courses

Home Page: https://htmlacademy.ru/intensive

License: MIT License

JavaScript 100.00%
eslint htmlacademy intensive-javascript

eslint-config-htmlacademy's Introduction

eslint-config-htmlacademy

ESLint shareable config for the HTML Academy courses

Installation

npm install --save-dev eslint-config-htmlacademy

Package requires eslint. You must install it manually.

Usage

Once the eslint-config-htmlacademy package is installed, you can use it by specifying htmlacademy in the extends section of your ESLint configuration.

For validating Vanilla JS project use vanilla version:

{
  "parserOptions": {
    "ecmaVersion": 2023,
    "sourceType": "module"
  },
  "env": {
    "es2023": true,
    "browser": true
  },
  "extends": "htmlacademy/vanilla",
  "rules": {
    // Additional rules...
  }
}

For validating React project use react version (htmlacademy/react includes react/recommended):

{
  "parserOptions": {
    "ecmaVersion": 2019,
    "sourceType": "module"
  },
  "env": {
    "es2017": true,
    "browser": true
  },
  "extends": "htmlacademy/react",
  "rules": {
    // Additional rules...
  }
}

For validating React project with TypeScript use react-typescript version (htmlacademy/react-typescript includes react/recommended, @typescript-eslint/recommended and @typescript-eslint/recommended-requiring-type-checking).

Before using eslint-config-htmlacademy make sure you have TypeScript, @typescript-eslint/parser, @typescript-eslint/eslint-plugin installed:

$ npm i --save-dev typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin
{
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "parserOptions": {
    "ecmaVersion": 2020,
    "sourceType": "module",
    "project": [
      "tsconfig.json" // path to your tsconfig file
    ]
  },
  "env": {
    "es2017": true,
    "browser": true
  },
  "extends": "htmlacademy/react-typescript",
  "rules": {
    // Additional rules...
  }
}

Caution! htmlacademy/react and htmlacademy/react-typescript doesn't include react-hooks/rules-of-hooks and react-hooks/exhaustive-deps because in our courses we use CRA (Create React App) which includes these plugins out of box. Install them yourself if necessary.

Caution! If you're wanting to use toBeCalled and similar matches in jest tests, you can use next option for eslintConfig:

"eslintConfig": {
  "overrides": [
    {
      "files": ["*test*"], // regExp to answer the question "How to find your tests?"
      "rules": {
        "@typescript-eslint/unbound-method": "off",
        "jest/unbound-method": "error"
      }
    }
  ]
}

Why this is necessary, you can read on the next page.

For validating Node project use node version (htmlacademy/node includes htmlacademy/vanilla, plugin:@typescript-eslint/recommended and plugin:node/recommended).

Before using eslint-config-htmlacademy make sure you have TypeScript and @typescript-eslint/parser installed:

$ npm i --save-dev typescript @typescript-eslint/parser

Then install the plugin:

$ npm i --save-dev @typescript-eslint/eslint-plugin
{
  "env": {
    "es2021": true,
    "node": true
  },
  "parserOptions": {
    "ecmaVersion": 2021,
    "sourceType": "module"
  },
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "extends": "htmlacademy/node",
  "rules": {
    // Additional rules...
  }
}

Caution!

  • htmlacademy/node aimed at using Typescript.
  • htmlacademy/node recommends a use of the "engines" field of package.json, because our package includes plugin:node/recomended. The "engines" field is used by node/no-unsupported-features/* rules.
  • htmlacademy/node uses ES6 modules and the rules are aimed precisely at this approach of connecting modules.

eslint-config-htmlacademy's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eslint-config-htmlacademy's Issues

Add no-unused-vars args: after-used config

Now we can's use snippets like this

[1, 2, 3, 4].filter(function(el, i){
  return i % 2;
});

without lint error, and we must disable eslint or do this hack

[1, 2, 3, 4].filter(function(_el, i){
  return i % 2;
});

I propose add option of no-unused-vars``args: after-used config. I will resolve the problem.

eslint-plugin-import

Запретить многострочную деструктуризацию в import
Добавить eslint-plugin-import было бы не лишним, просто чтобы избегать тупых ошибок.

Разные скобки перед функциями

'space-before-function-paren': ['error', {named: 'never', anonymous: 'always'}],

Почему мы в одном случае просим пробел перед скобками, а в другом нет? Нет единообразия. А единообразие это не только идеология и стилистика, это еще и копипаст. Например, если я написал:

elem.addEventListener('click', function() {}); /* без пробела */

а потом понял что нет, все-таки мне нужно эту функцию поименовать и вынести отдельно:

const elemClickHandler = function () {}; /* с пробелом */
elem.addEventListener('click', elemClickHandler); 

мне нужно не только перенести функцию в новое место, мне еще нужно сделать лишнее движение на постановку пробела.

Неудобненько же? Есть смысл оставить один вариант?

Remove continuation limitations

There is no reason to have special indent for continuation.

Here is not principle difference for this situations:

describe(`Generate JSON command`, function () {
  it(`should fail on not existing folder`, function () {
    const tempFileName = `${__dirname}/folder/testfile.json`;
    return generateCommand.execute(tempFileName).
        then(() => {
          assert.fail(`Path ${tempFileName} should not be available`);
        }).
        catch((e) => assert.ok(e));
  });
};
describe(`Generate JSON command`, function () {
  it(`should fail on not existing folder`, function () {
    const tempFileName = `${__dirname}/folder/testfile.json`;
    return generateCommand.execute(tempFileName).
      then(() => {
        assert.fail(`Path ${tempFileName} should not be available`);
      }).
      catch((e) => assert.ok(e));
  });
};

no-empty в пустом catch

Получаю no-empty ошибку если внутри catch ничего не будет. Пример для теста:

try {
  client.emit('message', JSON.stringify(data));
} catch (ignore) {
  // empty catch
}

Increase `max-nested-callbacks` to 5

Due to callback nature of tests, like mocha it makes really difficult to write tests with limit of 3 nested callbacks.
I think we can increase this limit to 5.

Bump `eslint` to `9.0.0`

Начиная с этой мажорки стилистические правила будут спамить про то, что они deprecated. Поэтому при обновлении надо ещё и @stylistic/eslint-plugin прикрутить.

Кроме того, теперь устаревший конфиг (не flat) подцеплять как-то по-особенному. Я даже разбираться не стал, проще на flat переделать, у которого имя обязательно eslint.config.js.

В общем работы много. Я всё воскресенье потратил. Немного помог их новый инспектор, но только немного — наглядно выявляет депрекейты (чтобы заменить их на плагинные), и дубликаты помогает отловить.

Удалить правило про `CRLF`

Т.к. это делает git автоматически на коммите, то смысла проверять CRLF я не вижу, рул можно смело выкинуть

indent

Два пробела везде, при разрыве строки: 4.

Add rule "Suggest using const"

I suggest adding a rule to eslint:

rules:
  prefer-const: error

This rule will underline the variable if posible use const instead let.

Перейти с Travis на GitHub Actions

Travis теперь платный после N-количества проверок. Пора мигрировать на GitHub Actions, пока мы не стали исчерпывать лимит.

trailing commas

'comma-dangle': ['error', 'only-multiline'],

"При создании непустых объектов и массивов не используются «висячие» запятые"

"only-multiline" allows (but does not require) trailing commas when the last element or property is in a different line than the closing ] or } and disallows trailing commas when the last element or property is on the same line as the closing ] or }
https://eslint.org/docs/rules/comma-dangle

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.