在Typescript项目中,如何优雅的使用ESLint和Prettier

19,167 阅读5分钟

  对于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来规范代码

原文在我的博客中: github.com/fortheallli…

欢迎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的影响。