Как внедрить стандарты разработки, чтобы никто не пострадал

Как внедрить стандарты разработки, чтобы никто не пострадал

Александра Шинкевич (@neesoglasnaja)

Кто я?

О чем буду говорить?

Guidelines   VS   Styleguide

Guidelines

Styleguide

Code Style

Правила, по которым надо писать код

Be Batman

Linters

Автоматическая проверка кода

Linters

Работают, только если...

С чего начать?

С настройки редактора

.editorconfig

Из коробки

Есть плагин

Формат .editorconfig

root = true
 
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_style = space
indent_size = 4
 
[*.{md,jade}]
indent_style = tab

HTML

HTML

yaniswang/HTMLHint

npm install htmlhint -g

htmlhint test.html

.htmlhintrc

{
   "tagname-lowercase": true,
   "attr-lowercase": true,
   "attr-value-double-quotes": true,
   "doctype-first": true,
   "tag-pair": true,
   "spec-char-escape": true,
   "id-unique": true,
   "src-not-empty": true,
   "attr-no-duplication": true,
   "title-require": true
}

npm install --save-dev gulp-htmlhint

 
const htmlhint = require('gulp-htmlhint');
gulp
   .src('./src/*.html')
   .pipe(htmlhint());

npm install --save-dev grunt-htmlhint

 
grunt.loadNpmTasks('grunt-htmlhint');
...
htmlhint: {
  options: {
    htmlhintrc: '.htmlhintrc'
  },
}

npm install --save-dev htmlhint-loader

 
module.exports = {
  module: {
    rules: [{
      enforce: 'pre',
      test: /\.html/,
      loader: 'htmlhint-loader',
      exclude: /node_modules/
    }]
  }
}

На любой вкус

CSS

CSS

Stylelint

stylelint/stylelint

Stylelint

.stylelintrc

{
  "extends": "stylelint-config-recommended",
  "rules": {
    "at-rule-no-unknown": [ true, {
      "ignoreAtRules": ["extends"]
    }],
    "block-no-empty": null,
    "unit-whitelist": ["em", "rem", "s"]
  }
}

npm install -g stylelint

stylelint "styles/*.css"

Плагины для редакторов

VimEmacsAtomVSCodeSublime Text

stylelint.io/editor-plugins

WebStorm

WebStorm Stylelint integration
Stylefmt

morishitter/stylefmt

npm install stylelint gulp-stylelint --save-dev

 
const stylelint = require('gulp-stylelint');
gulp
   .src('./src/*.css')
   .pipe(gulpStylelint({
      reporters: [
        { formatter: 'string', console: true }
      ]
   }));

npm install stylelint grunt-stylelint --save-dev

 
grunt.loadNpmTasks('grunt-stylelint');
...
grunt.initConfig({
  stylelint: {
    all: ['css/**/*.css', 'sass/**/*.scss']
  }
});

npm install stylelint-webpack-plugin --save-dev

 
const StyleLintPlugin = require('stylelint-webpack-plugin');
 
module.exports = {
  plugins: [
    new StyleLintPlugin(options),
  ]
}

Хочется больше?

CSScomb

CSSComb

CSSComb

npm install csscomb -g

csscomb assets/css

.csscomb.json

{
  "always-semicolon": true,
  "eof-newline": true,
  "leading-zero": true,
  "quotes": "single",
  ...,
  "sort-order": [
    [
      "position",
      "z-index"
    ], [
      "display",
      "visibility"
    ]
  ]
}

Плагины для редакторов

VimEmacsAtomVSCodeSublime TextBrackets

davidhund/styleguide-generators

JavaScript

JS

ESLint

eslint/eslint

ESLint

.eslintrc

{
  "parserOptions": {
    "parser": "babel-eslint",
    "sourceType": "module"
  },
  "env": { "browser": true },
  "extends": ["airbnb-base"],
  "plugins": ["vue"],
  "rules": {
    "semi": ["error", "always"],
    "no-debugger": "warn"
  }
}

npm install -g eslint

eslint --init

eslint scripts/*.js

npm install gulp-eslint --save-dev

 
const eslint = require('gulp-eslint');
gulp
   .src('./scripts/*.js')
   .pipe(eslint())
   .pipe(eslint.format())
   .pipe(eslint.failAfterError());

npm install grunt-eslint --save-dev

 
require('load-grunt-tasks')(grunt);
 
grunt.initConfig({
  eslint: {
    target: ['file.js']
  }
});

npm install eslint eslint-loader --save-dev

 
module.exports = {
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: "eslint-loader",
      options: { emitError: true }
    }]
  }
}

Плагины для редакторов

VimEmacsAtomVSCodeSublime Text

eslint.org/integrations

250+ правил?!

StandardJS

StandardJS

Airbnb ESLint config

Airbnb ESLint

А если не просто JS?

prettier/prettier

usejsdoc.org

Запрещаем коммитить плохой код

.git/hooks/pre-commit

#! /bin/bash
if !(npm run lint:js --silent)
  exit 1;
fi

npm install --save-dev pre-commit

 
{
  "name": "my-project",
  "scripts": {
    "lint:js": "eslint ./js/*.js",
    "test": "echo '🤣 No' && exit 1"
  },
  "pre-commit": [
    "lint:js",
    "test"
  ]
}

Выбери свой вариант

Как работать с репозиторием

Проблема 1.
Слишком строгие правила

Решение: понижать в local-dev-сборке «мешающие» свойства доwarn

Пример для Webpack

const isLocal = process.env.ENV_LOCAL === "local";
 
module.exports = {
  module: {
    rules: [{
      ...
      loader: "eslint-loader",
      options: {
        configFile: isLocal ? ".local-dev.eslintrc" : ".eslintrc"
      }
    }]
  }
}

Проблема 2.
Плохой код попадает в репозиторий

Решение: делать проверки в CI

Bitbucket Pipelines

pipelines:
  default:
    - step:
        caches:
          - node
        name: Source code linting
        script:
          - npm i
          - npm run lint

Подводя итог

Материалы по теме

Вопросы?