ESLint+Prettier统一TypeScript代码风格

4,113 阅读3分钟

加分号还是不加分号?tab还是空格?你还在为代码风格与同事争论得面红耳赤吗?

关于代码风格,我们很难区分谁对谁错,不同的人有不同偏好,唯有强制要求才能规避争论。

本文将介绍,如何使用ESLint + Prettier来统一我们的前端代码风格(这里以React项目为例)。

Prettier

Prettier是一个流行的代码格式化工具的名称,它能够解析代码,使用你自己设定的规则来重新打印出格式规范的代码。

Prettier具有以下几个有优点: 可配置化 支持多种语言 集成多数的编辑器 简洁的配置项

它支持的语言有:

使用Prettier可以将代码格式化成统一的风格。 下面使用官方的例子来简单的了解下它的工作方式。 Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne()
);

安装

npm install prettier

创建配置文件

在项目根目录下创建.prettierrc.js文件进行配置:

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

ESLint

提起TypeScript代码检查工具,我们首先可能会想到TSLint。但是由于性能问题,TypeScript 官方决定全面采用 ESLint,甚至把仓库(Repository)作为测试平台,而 ESLint 的 TypeScript 解析器也成为独立项目,专注解决双方兼容性问题。而 TSLint 将放弃维护。 因此,我们决定采用 ESLint

安装

首先我们安装eslint及使用ESLint来为你运行Prettier所需的一些包

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

创建配置文件

在项目根目录下创建.eslintrc.js文件进行配置:

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 configuration in 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相关校验规则
        "react/jsx-indent": [2, 4],
        "react/jsx-no-undef": [2, { allowGlobals: true }],
        "jsx-control-statements/jsx-use-if-tag": 0
    }
};

强制校验和格式化

讲到这里两个工具配合使用已经讲好了,但是这些步骤都依赖于人工自觉,要做到一点点强制功能,我们可以在 git commit 前强制代码格式化和代码校验。

安装

npm install --save-dev husky lint-staged

修改 package.json

{
  "name": "project-name",
  // ...
  "scripts": {
    "eslint": "eslint --ext .tsx,.ts --fix ./src", // 需要在这里指定校验.tsx,.ts后缀的文件
  },
  "husky": {
    "hooks": {
      // git commit 前强制代码格式化和代码校验
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,tsx}": [
      "npm run eslint",
      "prettier .prettierrc.js --write",
      "git add"
    ]
  }
}