@labeg/code-style 3.0.9 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/.eslintrc.js +101 -58
  2. package/README.md +117 -102
  3. package/package.json +2 -1
package/.eslintrc.js CHANGED
@@ -1,19 +1,48 @@
1
- module.exports = {
2
- parser: "@typescript-eslint/parser",
3
- parserOptions: {
4
- project: "tsconfig.json",
5
- sourceType: "module",
6
- ecmaVersion: "latest",
7
- ecmaFeatures: {
8
- jsx: true
1
+ "use strict"
2
+
3
+ /**
4
+ * Good instruction:
5
+ * https://duncanleung.com/eslint-mixed-javascript-typescript-files-codebase/
6
+ */
7
+
8
+ const jsAndTsRules = {
9
+ "sort-imports": "off", // Need found sorter
10
+ "max-len": [
11
+ "error", {
12
+ code: 140,
13
+ comments: 140
9
14
  }
10
- },
15
+ ], // More nice, for modern screens
16
+ "padded-blocks": [
17
+ "error", {
18
+ classes: "always",
19
+ blocks: "never",
20
+ switches: "never"
21
+ }
22
+ ], // More nice
23
+ "function-call-argument-newline": ["error", "consistent"], // More nice
24
+ "quote-props": ["error", "as-needed"], // More nice
25
+ "sort-keys": "off", // More nice
26
+ "class-methods-use-this": "off", // False positives
27
+ "one-var": ["error", "never"], // More nice
28
+ "no-ternary": "off", // More nice
29
+ "multiline-ternary": ["error", "always-multiline"], // More nice
30
+ "array-element-newline": ["error", "consistent"], // More nice
31
+ "operator-linebreak": ["error", "after"], // More nice
32
+ "no-void": "off", // Strange rule
33
+ "max-params": ["error", {max: 4}], // Maybe later?
34
+ "no-bitwise": "off", // Used in many projects
35
+ "prefer-named-capture-group": "off", // Maybe later?
36
+ "dot-location": ["error", "property"], // More nice
37
+ "no-inline-comments": "off", // Maybe later?
38
+ "line-comment-position": "off", // Maybe later?
39
+
40
+ "no-duplicate-imports": "off" // Bug, remove later
41
+ };
42
+
43
+ module.exports = {
11
44
  extends: [
12
- "eslint:all",
13
- "plugin:react/all",
14
- "plugin:react-hooks/recommended",
15
- "plugin:@typescript-eslint/all",
16
- "plugin:jsx-a11y/strict"
45
+ "eslint:all" // There is no React because they are used strictly with Typescript.
17
46
  ],
18
47
  root: true,
19
48
  env: {
@@ -28,49 +57,63 @@ module.exports = {
28
57
  }
29
58
  },
30
59
  rules: {
31
- "sort-imports": "off", // need found sorter
32
- "max-len": ["error", { code: 140, comments: 140 }], // for modern screens
33
- "padded-blocks": ["error", { classes: "always", blocks: "never", switches: "never" }], // more nice
34
- "function-call-argument-newline": ["error", "consistent"], // maybe later?
35
- "quote-props": ["error", "as-needed"], // more nice
36
- "sort-keys": "off", // more nice
37
- "class-methods-use-this": "off", // false positives
38
- "one-var": ["error", "never"], // more nice
39
- "no-ternary": "off", // more nice
40
- "multiline-ternary": ["error", "always-multiline"], // more nice
41
- "array-element-newline": ["error", "consistent"], // more nice
42
- "operator-linebreak": ["error", "after"], // more nice
43
- "no-void": "off", // strange rule
44
- "max-params": ["error", { "max": 4 }], // maybe later?
45
- "no-bitwise": "off", // needed
46
- "prefer-named-capture-group": "off", // maybe later?
47
- "dot-location": ["error", "property"], // more nice
48
- "no-inline-comments": "off", // maybe later?
49
- "line-comment-position": "off", // maybe later?
50
-
51
- "react/jsx-no-literals": "off", // broken rule, not work with ??
52
- "react/jsx-max-depth": ["error", { "max": 10 }], // to small by default
53
- "react/jsx-filename-extension": ["error", { extensions: [".tsx"] }], // for typescript
54
- "react/function-component-definition": ["error", { "namedComponents": "arrow-function" }], // same as eslint func-styles
55
- "react/no-danger": "off", // for insert html
56
- "react/forbid-component-props": "off", // conflict with styled-components
57
- "react/jsx-uses-react": "off", // https://ru.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
58
- "react/react-in-jsx-scope": "off", // https://ru.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
59
- "react/sort-comp": "off", // need write priority
60
+ ...jsAndTsRules
61
+ },
62
+ overrides: [
63
+ {
64
+ files: ["**/*.{ts,tsx}"],
65
+ settings: {
66
+ "import/parsers": {
67
+ "@typescript-eslint/parser": [".ts", ".tsx"]
68
+ },
69
+ "import/resolver": {
70
+ typescript: {
71
+ project: "./tsconfig.json"
72
+ }
73
+ }
74
+ },
75
+ parser: "@typescript-eslint/parser",
76
+ parserOptions: {
77
+ project: "tsconfig.json",
78
+ tsconfigRootDir: __dirname,
79
+ sourceType: "module",
80
+ ecmaVersion: "latest",
81
+ ecmaFeatures: {
82
+ jsx: true
83
+ }
84
+ },
85
+ extends: [
86
+ "eslint:all",
87
+ "plugin:@typescript-eslint/all",
88
+ "plugin:react/all",
89
+ "plugin:react-hooks/recommended",
90
+ "plugin:jsx-a11y/strict"
91
+ ],
92
+ rules: {
93
+ ...jsAndTsRules,
94
+ "@typescript-eslint/no-inferrable-types": "off", // Need for reflection
95
+ "@typescript-eslint/no-magic-numbers": "off",
96
+ "@typescript-eslint/prefer-readonly-parameter-types": "off", // Wrong immutable undestand
97
+ "@typescript-eslint/no-floating-promises": "off", // Block async promises
98
+ "@typescript-eslint/no-extra-parens": "off", // Conflict with react best practise in jsx
99
+ "@typescript-eslint/promise-function-async": "off", // More nice
100
+ "@typescript-eslint/no-misused-promises": ["error", {checksVoidReturn: false}], // More nice
101
+ "@typescript-eslint/naming-convention": "off", // Bad with react func components
102
+ "@typescript-eslint/no-confusing-void-expression": "off", // More nice
103
+ "@typescript-eslint/member-ordering": "off", // Need correct priority
60
104
 
61
- "@typescript-eslint/no-inferrable-types": "off", // need for reflection
62
- "@typescript-eslint/no-magic-numbers": "off",
63
- "@typescript-eslint/prefer-readonly-parameter-types": "off", // wrong immutable undestand
64
- "@typescript-eslint/no-floating-promises": "off", // block async promises
65
- "@typescript-eslint/no-extra-parens": "off", // conflict with react best practise in jsx
66
- "@typescript-eslint/promise-function-async": "off", // more nice
67
- "@typescript-eslint/no-misused-promises": ["error", { "checksVoidReturn": false }], // more nice
68
- "@typescript-eslint/naming-convention": "off", // bad with react func components
69
- "@typescript-eslint/no-confusing-void-expression": "off", // more nice
70
- "@typescript-eslint/member-ordering": "off", // need correct priority
105
+ "@typescript-eslint/keyword-spacing": "off", // Bug, remove later
106
+ "@typescript-eslint/no-import-type-side-effects": "off", // Bug, remove later
71
107
 
72
- "@typescript-eslint/keyword-spacing": "off", // bug, remove later
73
- "@typescript-eslint/no-import-type-side-effects": "off", // bug, remove later
74
- "no-duplicate-imports": "off" // bug, remove later
75
- }
76
- };
108
+ "react/jsx-filename-extension": ["error", {extensions: [".tsx"]}], // Added typescript file extension
109
+ "react/jsx-no-literals": "off", // Broken rule, not work with ??
110
+ "react/jsx-max-depth": ["error", {max: 10}], // To small by default
111
+ "react/function-component-definition": ["error", {namedComponents: "arrow-function"}], // Same as eslint func-styles
112
+ "react/forbid-component-props": "off", // Conflict with styled-components
113
+ "react/jsx-uses-react": "off", // https://ru.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
114
+ "react/react-in-jsx-scope": "off", // https://ru.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
115
+ "react/sort-comp": "off" // Need write priority
116
+ }
117
+ }
118
+ ]
119
+ };
package/README.md CHANGED
@@ -1,103 +1,118 @@
1
- ![David](https://img.shields.io/david/LabEG/code-style.svg)
2
- ![David](https://img.shields.io/david/dev/LabEG/code-style.svg)
3
- ![GitHub](https://img.shields.io/github/license/LabEG/code-style.svg)
4
-
5
-
6
- # CodeStyle
7
- В этом репозитории я собираю файлы стилей для облегчения синхронизации между проектами.
8
-
9
-
10
- ## Рекомендации
11
- ### Не заканчивать строку ничем
12
- Строка всегда должна заканчиваться знаком конца строки или оператором, например ; или +. Делается это для того что бы глядя всего на одну строку знать есть ли у команды продолжение на следующей строке или нет. Тем самым для понимания надо прочитать всего одну строчку вместо двух, что экономит время. А отсутствие ; в конце команды может привести к ошибкам исполнения.
13
-
14
- ```Typescript
15
- /**
16
- * Оператор в конце строки
17
- */
18
-
19
- // Плохо. Глядя на первую строчку не понятно это конец команды или надо искать продолжение
20
- let sample = sample.sample.sample
21
- + sample.sample.sample;
22
-
23
- // Хорошо. Глядя на первую строчку видно что команда не заканчивается и стоит искать продолжение на следующей
24
- let sample = sample.sample.sample +
25
- sample.sample.sample;
26
-
27
- /**
28
- * Знак конца строки
29
- */
30
-
31
- // Плохо. Выведет 2,2 хотя ожидается 0,2
32
- var a = 1, b = 0
33
- if(a>b) a=b
34
- -b > 0 ? b=1 : b=2;
35
- alert([a,b])
36
-
37
- // Плохо, выдаст ошибку исполнения
38
- var i,s
39
- s="here is a string"
40
- i=0
41
- /[a-z]/g.exec(s)
42
-
43
- ```
44
-
45
- ### Фигурный скобки в if
46
- Даже если после блока if идет всего 1 команда, фигурные скобки все равно ставить обязательно.
47
- Во первых, вы сэкономите время себе же в будующем когда понадобиться срочно дополнить условие.
48
- Во вторых, очень часто люди не замечают что строка относится к условию if и при рефакторинге или удалении строки забывают про if, из-за чего if начинает влиять на другую строчку кода.
49
-
50
- ```Typescript
51
- // Плохо
52
- if (n > 10) alert("Плохо");
53
-
54
- // Плохо
55
- if (n > 10)
56
- alert("Плохо");
57
-
58
- // Хорошо
59
- if (n > 10) {
60
- alert("Хорошо");
61
- }
62
- ```
63
-
64
- ### Используйте двойные кавычки
65
- Изначально в более взрослых языках используются " для написания строк, в JS для более простого ескейпа было принято писать '. Так было проще для JS разработчиков. Но теперь существуют шаблонные строки которые справляются с этой задаче много лучше. К тому же коллегам с бекенда будет проще понимать ваш код в случае необходимости.
66
-
67
- ```Typescript
68
- const message = "булочек";
69
- const count = 5;
70
-
71
- // Плохо
72
- const data = 'Отправляю "бабушке" ' + count * 5 + ' ' + message + '.';
73
-
74
- // Хорошо
75
- const data = `Отправляю "бабушке" ${count * 5} ${message}.`;
76
- ```
77
-
78
- ### Длина строки 120 символов и отступ 4 пробела
79
- У всех разработчиков разные мониторы, у кого то большие, у кого то маленькие, а кто то вообще через консоль работает. Поэтому оптимальным размером строки является 120 символов. А использование 4 проблема для отступа является оптимальным решением для определения уровня вложености. Некоторые предпочитают использовать 2 пробела для того что бы на одну строку больше влазило, но это является плохой практикой, т.к. увеличивает нагрузку на глаза при определении уровня вложености. Вместо того что бы впихивать на одну строчку больше кода, лучше использовать более удачное форматирование, например писать более простые функции и использовать "функциональный" стиль для цепочек методов объекта.
80
-
81
- Для вдохновления предлагаю взглянуть на [ядро Linux](https://github.com/torvalds/linux/blob/master/kernel/acct.c). Посмотрите как просто написано такой огромный и сложный продукт, а длина строки всего 80 символов.
82
-
83
- ```Typescript
84
- export class Tabs extends Base {
85
- // ...
86
- private onTabClick(tab: Tab): void {
87
-
88
- if (tab.active) {
89
-
90
- if (!this._slotElement
91
- .assignedNodes()
92
- .some((node: Node) => node instanceof Tab && node.active === true)) {
93
-
94
- const offset = tab.offsetLeft - tab.parentElement!.offsetLeft;
95
- const width = tab.offsetWidth;
96
- this._lineElement.style.marginLeft = `${offset + width / 2}px`;
97
- this._lineElement.style.width = `0`;
98
-
99
- }
100
- }
101
- }
102
- }
1
+ ![David](https://img.shields.io/david/LabEG/code-style.svg)
2
+ ![David](https://img.shields.io/david/dev/LabEG/code-style.svg)
3
+ ![GitHub](https://img.shields.io/github/license/LabEG/code-style.svg)
4
+
5
+
6
+ # CodeStyle
7
+ В этом репозитории я собираю файлы стилей для облегчения синхронизации между проектами.
8
+
9
+ ## Подключение
10
+ Для подключение необходимо установить пакет командой:
11
+ ```Bash
12
+ npm i -D @labeg/code-style
13
+ ```
14
+
15
+ Далее в вашь файл eslint config необходимо добавить следующую строчку:
16
+ ```Javascript
17
+ module.exports = {
18
+ extends: ["@labeg/code-style"],
19
+ rules:{
20
+ // override here
21
+ }
22
+ };
23
+ ```
24
+
25
+ ## Рекомендации
26
+ ### Не заканчивать строку ничем
27
+ Строка всегда должна заканчиваться знаком конца строки или оператором, например ; или +. Делается это для того что бы глядя всего на одну строку знать есть ли у команды продолжение на следующей строке или нет. Тем самым для понимания надо прочитать всего одну строчку вместо двух, что экономит время. А отсутствие ; в конце команды может привести к ошибкам исполнения.
28
+
29
+ ```Typescript
30
+ /**
31
+ * Оператор в конце строки
32
+ */
33
+
34
+ // Плохо. Глядя на первую строчку не понятно это конец команды или надо искать продолжение
35
+ let sample = sample.sample.sample
36
+ + sample.sample.sample;
37
+
38
+ // Хорошо. Глядя на первую строчку видно что команда не заканчивается и стоит искать продолжение на следующей
39
+ let sample = sample.sample.sample +
40
+ sample.sample.sample;
41
+
42
+ /**
43
+ * Знак конца строки
44
+ */
45
+
46
+ // Плохо. Выведет 2,2 хотя ожидается 0,2
47
+ var a = 1, b = 0
48
+ if(a>b) a=b
49
+ -b > 0 ? b=1 : b=2;
50
+ alert([a,b])
51
+
52
+ // Плохо, выдаст ошибку исполнения
53
+ var i,s
54
+ s="here is a string"
55
+ i=0
56
+ /[a-z]/g.exec(s)
57
+
58
+ ```
59
+
60
+ ### Фигурный скобки в if
61
+ Даже если после блока if идет всего 1 команда, фигурные скобки все равно ставить обязательно.
62
+ Во первых, вы сэкономите время себе же в будующем когда понадобиться срочно дополнить условие.
63
+ Во вторых, очень часто люди не замечают что строка относится к условию if и при рефакторинге или удалении строки забывают про if, из-за чего if начинает влиять на другую строчку кода.
64
+
65
+ ```Typescript
66
+ // Плохо
67
+ if (n > 10) alert("Плохо");
68
+
69
+ // Плохо
70
+ if (n > 10)
71
+ alert("Плохо");
72
+
73
+ // Хорошо
74
+ if (n > 10) {
75
+ alert("Хорошо");
76
+ }
77
+ ```
78
+
79
+ ### Используйте двойные кавычки
80
+ Изначально в более взрослых языках используются " для написания строк, в JS для более простого ескейпа было принято писать '. Так было проще для JS разработчиков. Но теперь существуют шаблонные строки которые справляются с этой задаче много лучше. К тому же коллегам с бекенда будет проще понимать ваш код в случае необходимости.
81
+
82
+ ```Typescript
83
+ const message = "булочек";
84
+ const count = 5;
85
+
86
+ // Плохо
87
+ const data = 'Отправляю "бабушке" ' + count * 5 + ' ' + message + '.';
88
+
89
+ // Хорошо
90
+ const data = `Отправляю "бабушке" ${count * 5} ${message}.`;
91
+ ```
92
+
93
+ ### Длина строки 120 символов и отступ 4 пробела
94
+ У всех разработчиков разные мониторы, у кого то большие, у кого то маленькие, а кто то вообще через консоль работает. Поэтому оптимальным размером строки является 120 символов. А использование 4 проблема для отступа является оптимальным решением для определения уровня вложености. Некоторые предпочитают использовать 2 пробела для того что бы на одну строку больше влазило, но это является плохой практикой, т.к. увеличивает нагрузку на глаза при определении уровня вложености. Вместо того что бы впихивать на одну строчку больше кода, лучше использовать более удачное форматирование, например писать более простые функции и использовать "функциональный" стиль для цепочек методов объекта.
95
+
96
+ Для вдохновления предлагаю взглянуть на [ядро Linux](https://github.com/torvalds/linux/blob/master/kernel/acct.c). Посмотрите как просто написано такой огромный и сложный продукт, а длина строки всего 80 символов.
97
+
98
+ ```Typescript
99
+ export class Tabs extends Base {
100
+ // ...
101
+ private onTabClick(tab: Tab): void {
102
+
103
+ if (tab.active) {
104
+
105
+ if (!this._slotElement
106
+ .assignedNodes()
107
+ .some((node: Node) => node instanceof Tab && node.active === true)) {
108
+
109
+ const offset = tab.offsetLeft - tab.parentElement!.offsetLeft;
110
+ const width = tab.offsetWidth;
111
+ this._lineElement.style.marginLeft = `${offset + width / 2}px`;
112
+ this._lineElement.style.width = `0`;
113
+
114
+ }
115
+ }
116
+ }
117
+ }
103
118
  ```
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@labeg/code-style",
3
- "version": "3.0.9",
3
+ "version": "3.1.1",
4
+ "main": ".eslintrc.js",
4
5
  "scripts": {
5
6
  "prepublishOnly": "npm version patch"
6
7
  },