With or without a semicolon? TAB or space? Are you still arguing red in the face with colleagues about code style?

When it comes to code style, it’s hard to tell who’s right and who’s wrong, and different people have different preferences, so coercion is the only way to avoid debate.

This article will show how ESLint + Prettier can be used to unify our front-end code style (take the React project as an example).

Prettier

Prettier is the name of a popular code formatting tool that parses code and reprints it using rules you set for yourself.

Prettier has the following advantages: Configurability Simple configuration items integrated into most editors in multiple languages

It supports the following languages:

  • JavaScript, including ES2017
  • JSX
  • Angular
  • Vue
  • Flow
  • TypeScript
  • CSS, Less, and SCSS
  • HTML
  • JSON
  • GraphQL
  • Markdown, including GFM and MDX
  • YAML

Use Prettier to format code into a uniform style. Here’s a quick look at how it works using the official example. Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
Copy the code

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne()
);
Copy the code

The installation

npm install prettier
Copy the code

Creating a Configuration File

Create the. Prettierrc.js file in the root directory of the project and configure it:

module.exports = {
    printWidth: 120,
    tabWidth: 4,
    singleQuote: true,
    semi: true,
    trailingComma: 'es5',
    bracketSpacing: true,
    jsxBracketSameLine: true,
    arrowParens: 'always',
    parser: 'typescript'
};
Copy the code

ESLint

TSLint is probably the first TypeScript code-checking tool that comes to mind. However, due to performance issues, TypeScript officially decided to adopt ESLint entirely, even using a Repository as its testing platform, while ESLint’s TypeScript parser became a separate project focused on compatibility issues. TSLint will give up maintenance. So, we decided to go with ESLint.

The installation

First we install ESLint and use esLint to run the packages Prettier needs for you

npm install eslint eslint-config-prettier eslint-plugin-prettier eslint-plugin-react eslint-plugin-jsx-control-statements babel-eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
Copy the code

Creating a Configuration File

Create the.eslintrc.js file in the project root directory to configure:

module.exports = {
    parser: '@typescript-eslint/parser', // Specifies the ESLint parser
    extends: [
        'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
        'plugin:react/recommended'.'plugin:jsx-control-statements/recommended'.'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
        'plugin:prettier/recommended'. // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configurationin the extends array.
        'prettier/react']."settings": {
        "react": {
            "version": "detect",
        }
    },
    plugins: ['@typescript-eslint'.'react'.'jsx-control-statements'.'prettier'],
    env: {
        browser: true,
        node: true,
        es6: true,
        mocha: true.'jsx-control-statements/jsx-control-statements': true
    },
    globals: {
        $: true
    },
    rules: {
        'prettier/prettier': 1,
        'no-console': ['warn', { allow: ['warn'.'error']}],"eqeqeq": ['warn'.'always']."prefer-const": ['error', {"destructuring": "all"."ignoreReadBeforeAssign": true}].'@typescript-eslint/indent': ['error', 4, { VariableDeclarator: 4, SwitchCase: 1 }],
        '@typescript-eslint/no-unused-vars': 0."@typescript-eslint/interface-name-prefix": 0."@typescript-eslint/explicit-member-accessibility": 0."@typescript-eslint/no-triple-slash-reference": 0."@typescript-eslint/ban-ts-ignore": 0."@typescript-eslint/no-this-alias": 0."@typescript-eslint/triple-slash-reference": ['error', { "path": "always"."types": "never"."lib": "never"}], // React related verification rules"react/jsx-indent": [2, 4]."react/jsx-no-undef": [2, { allowGlobals: true}]."jsx-control-statements/jsx-use-if-tag": 0}};Copy the code

Enforce checksum formatting

The two tools have already been used together, but these steps rely on manual awareness. To do a little bit of coercion, we can force code formatting and verification before git commit.

The installation

npm install --save-dev husky lint-staged
Copy the code

Modify the package. The json

{
  "name": "project-name",
  // ...
  "scripts": {
    "eslint": "eslint --ext .tsx,.ts --fix ./src"TSX,.ts files},"husky": {
    "hooks"Enforce formatting and validation before git commit"pre-commit": "lint-staged"}},"lint-staged": {
    "*.{ts,tsx}": [
      "npm run eslint"."prettier .prettierrc.js --write"."git add"]}}Copy the code