ESLint+Prettier統一TypeScript代碼風格

加分號仍是不加分號?tab仍是空格?你還在爲代碼風格與同事爭論得面紅耳赤嗎?css

關於代碼風格,咱們很難區分誰對誰錯,不一樣的人有不一樣偏好,惟有強制要求才能規避爭論。html

本文將介紹,如何使用ESLint + Prettier來統一咱們的前端代碼風格(這裏以React項目爲例)。前端

Prettier

Prettier是一個流行的代碼格式化工具的名稱,它可以解析代碼,使用你本身設定的規則來從新打印出格式規範的代碼。vue

Prettier具備如下幾個有優勢: 可配置化 支持多種語言 集成多數的編輯器 簡潔的配置項node

它支持的語言有:react

使用Prettier能夠將代碼格式化成統一的風格。 下面使用官方的例子來簡單的瞭解下它的工做方式。 Inputgit

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
複製代碼

Outputes6

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne()
);
複製代碼

安裝

npm install prettier
複製代碼

建立配置文件

在項目根目錄下建立.prettierrc.js文件進行配置:github

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 將放棄維護。 所以,咱們決定採用 ESLinttypescript

安裝

首先咱們安裝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"
    ]
  }
}
複製代碼
相關文章
相關標籤/搜索