在Typescript項目中,如何優雅的使用ESLint和Prettier


  對於Typescript項目的編碼規範而言,主要有兩種選擇ESLint和TSLint。ESLint不僅能規範js代碼,通過配置解析器,也能規範TS代碼。此外由於性能問題,TypeScript 官方決定全面採用ESLint,甚至把倉庫作爲測試平臺,而 ESLint 的 TypeScript 解析器也成爲獨立項目,專注解決雙方兼容性問題。
  最近在我的項目的編碼規範中全量的用ESLint代替了TSLint,針對其中遇到的問題做一個記錄。

  • 用ESLint來規範Typescript代碼
  • 用ESLint來規範React代碼
  • 結合Prettier和ESLint來規範代碼
  • 在VSCode中使用ESLint
  • husky和lint-staged構建代碼工作流
  • gitlab的CI/CD來規範代碼

原文在我的博客中: https://github.com/forthealll...

歡迎star和收藏


一、用ESLint來規範Typescript代碼

首先安裝依賴:

npm i -d eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

這三個依賴分別是:

  • eslint: ESLint的核心代碼
  • @typescript-eslint/parser:ESLint的解析器,用於解析typescript,從而檢查和規範Typescript代碼
  • @typescript-eslint/eslint-plugin:這是一個ESLint插件,包含了各類定義好的檢測Typescript代碼的規範

安裝好這3個依賴包之後,在根目錄下新建.eslintrc.js文件,該文件中定義了ESLint的基礎配置,一個最爲簡單的配置如下所示:

module.exports = {

    parser:  '@typescript-eslint/parser', //定義ESLint的解析器
    extends: ['plugin:@typescript-eslint/recommended'],//定義文件繼承的子規範
    plugins: ['@typescript-eslint'],//定義了該eslint文件所依賴的插件
    env:{                          //指定代碼的運行環境
        browser: true,
        node: true,
    }                               
}
  • 在ts項目中必須執行解析器爲@typescript-eslint/parser,才能正確的檢測和規範TS代碼
  • env環境變量配置,形如console屬性只有在browser環境下才會存在,如果沒有設置支持browser,那麼可能報console is undefined的錯誤。

二、用ESLint來規範React代碼

如果在你的TS項目中同時使用了React,那麼爲了檢測和規範React代碼的書寫必須安裝插件eslint-plugin-react,然後增加配置:


module.exports = {

    parser:  '@typescript-eslint/parser',
    extends: [
    'plugin:react/recommended'  
    'plugin:@typescript-eslint/recommended'
    ],                              //使用推薦的React代碼檢測規範
    plugins: ['@typescript-eslint'],
    env:{                         
        browser: true,
        node: true,
    },
    settings: {             //自動發現React的版本,從而進行規範react代碼
        "react": {
            "pragma": "React",
            "version": "detect"
        }
    }, 
    parserOptions: {        //指定ESLint可以解析JSX語法
        "ecmaVersion": 2019,
        "sourceType": 'module',
        "ecmaFeatures":{
            jsx:true
        }
    }
    rules: {
    
    }
}

在Rules中可以自定義你的React代碼編碼規範。

三、結合Prettier和ESLint來規範代碼

  Prettier中文的意思是漂亮的、美麗的,是一個流行的代碼格式化的工具,我們來看如何結合ESLint來使用。首先我們需要安裝三個依賴:

npm i -g prettier eslint-config-prettier eslint-plugin-prettier

其中:

  • prettier:prettier插件的核心代碼
  • eslint-config-prettier:解決ESLint中的樣式規範和prettier中樣式規範的衝突,以prettier的樣式規範爲準,使ESLint中的樣式規範自動失效
  • eslint-plugin-prettier:將prettier作爲ESLint規範來使用

然後在項目的根目錄下創建.prettierrc.js文件:

module.exports =  {
    "printWidth": 120,
    "semi": false,
    "singleQuote": true,
    "trailingComma": "all",
    "bracketSpacing": false,
    "jsxBracketSameLine": true,
    "arrowParens": "avoid",
    "insertPragma": true,
    "tabWidth": 4,
    "useTabs": false  
  };

接着修改.eslintrc.js文件,引入prettier:

module.exports = {
    parser:  '@typescript-eslint/parser',
    extends:[ 
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended'
    ],
    settings: {
        "react": {
            "pragma": "React",
            "version": "detect"
        }
    },
    parserOptions: {
        "ecmaVersion": 2019,
        "sourceType": 'module',
        "ecmaFeatures":{
            jsx:true
        }
    },
    env:{
        browser: true,
        node: true,
    }  

上述新增的extends的配置中:

  • prettier/@typescript-eslint:使得@typescript-eslint中的樣式規範失效,遵循prettier中的樣式規範
  • plugin:prettier/recommended:使用prettier中的樣式規範,且如果使得ESLint會檢測prettier的格式問題,同樣將格式問題以error的形式拋出

## 四、在VSCode中集成ESLint配置

  爲了開發方便我們可以在VSCode中集成ESLint的配置,使得代碼在保存或者代碼變動的時候自動進行ESLint的fix過程。

  首先需要安裝VSCode的ESLint插件,安裝插件完畢後,在settings.json文件中修改其配置文件爲:

{
       "eslint.enable": true,  //是否開啓vscode的eslint
       "eslint.autoFixOnSave": true, //是否在保存的時候自動fix eslint
       "eslint.options": {    //指定vscode的eslint所處理的文件的後綴
           "extensions": [
               ".js",
               ".vue",
               ".ts",
               ".tsx"
           ]
       },
       "eslint.validate": [     //確定校驗準則
           "javascript",
           "javascriptreact",
           {
               "language": "html",
               "autoFix": true
           },
           {
               "language": "vue",
               "autoFix": true
           },
           {
               "language": "typescript",
               "autoFix": true
           },
           {
               "language": "typescriptreact",
               "autoFix": true
           }
       ]
}

主要注意的有兩點:

  • eslint.options中可以通過configFile屬性來執行eslint規範的絕對路徑,默認會向上查找,在根路徑中指定。
  • eslint.validate中必須通過{ language: XXX}的形式來指定typescript和typescriptreact

五、husky和lint-staged構建代碼工作流

  首先來看husky,Husky 能夠幫你阻擋住不好的代碼提交和推送,首先我們在package.json中定義如下的script:

 "scripts": {
   "lint": "eslint src --fix --ext .ts,.tsx "
}

接着在package.json定義husky的配置:

 "husky": {
   "hooks": {
      "pre-commit": "npm run lint"
    }
},

我們在git的hook的階段來執行相應的命令,比如上述的例子是在pre-commit這個hook也就是在提交之前進行lint的檢測。

  接着來看lint-staged,上述我們通過在husky的pre-comit這個hook中執行一個npm命令來做lint校驗。除了定義個npm lint命令外,我們也可以直接通過使用lint-staged,來在提交前檢測代碼的規範。
  使用lint-staged來規範代碼的方式如下,我們修改package.json文件爲:

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{.ts,.tsx}": [
      "eslint",
      "git add"
    ]
  }
}

同樣在git commit的時候會做lint的檢測。

六、gitlab的CI/CD來規範代碼

   僅僅通過git的hook來執行代碼的規範檢測有一個問題,我們可以在git commit的時候通過--no-verify來跳過代碼的規範檢測。但是某些情況下,我們對於某一個重要分支,該分支上的代碼必須完整通過代碼的規範檢測,此時我們可以使用gitlab的CI/CD。

   同樣在package.json中增加一個lint的npm 命令:

  "scripts": {
     "lint": "eslint src --fix --ext .ts,.tsx "
  }

然後在根目錄增加.gitlab-ci.yml文件,該文件中的配置爲:

stages:
  - lint

before_script:
  - git fetch --all
  - npm install 

lint:
  stage: lint
  script:
    - npm run lint
  only
    - 特定分支1
    - 特定分支2



  然後配置相應的gitlab runner,這裏不具體詳描,最後的結果就是在我們指定的分支上的提交或者merge都會進行所配置的命令檢測。這樣保證了特定分支不受git commit跳過操作--no-verify的影響。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章