react typescript工程的eslint配置

4,109 阅读2分钟

不知道什么时候,已经不使用tslint了呢。

TSLint 是一个很棒的工具。它是一个专门为基于上述 TypeScript AST 格式而编写的 linter。

然而tslint 主要的缺点是无法兼容eslint ,现在由于 eslint 的社区已经非常完善了,而 tslint 无法使用这些社区的成果,也无法将自己的成果回馈给社区,所以 tslint 背后的支持者 Palantir 已经宣布会逐渐废弃 tslint 以支持 typescript-eslint-parser。

也就是说,typescript-eslint-parser 和 tslint 的主要区别就是,他们是基于不同 AST 的 lint 工具, typescript-eslint-parser 可以兼容 eslint 的生态,可以跟 eslint 的各种插件一起使用,而 tslint 不可以。

TSLint 背后的支持者 Palantir 在 2019 年宣布,他们将弃用 TSLint,转而支持**typescript-eslint**以造福社区。您可以在此处阅读更多相关信息:https

://medium.com/palantir/tslint-in-2019-1a144c2317a9

怎么使用typescript-eslint呢?

安装

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

配置eslint,rules参考eslint.org/docs/rules/

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    
  'prettier',  
],  
plugins: ['eslint-plugin-react'],  
rules: {    
  // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs    
  // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  // 0:"off", 1:"warn", 2:"error"    
  semi: 2,    
  '@typescript-eslint/no-empty-interface': 0,    
  '@typescript-eslint/ban-types': [      
    2,      
    {  
      types: {          
        Function: {            
          message: 'Prefer a specific function type, like `() => void`.',          
        },       
       },      
      },    
    ],    
   'no-use-before-define': 0,    
   '@typescript-eslint/no-use-before-define': 2,    
   'no-shadow': 0,    
   '@typescript-eslint/no-shadow': 2  
},  
parserOptions: {    
  sourceType: 'module',    
  ecmaFeatures: {      jsx: true,    },  
},  
settings: {    
  react: {      
    version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use    
  },  
},

需要注意的是eslint有些和@typescript-eslint冲突的规则,需要调整:

解决“import React from 'react';”会报错问题

'no-use-before-define': 0,    
'@typescript-eslint/no-use-before-define': 2,    

解决enum类型定义报错问题

'no-shadow': 0,   
'@typescript-eslint/no-shadow': 2

配置vscode

{
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ],
}

学废了!