typescript结合prettier实现代码检测

typescript结合prettier实现代码检测

Posted by Xshellv on 2021-10-06

我们在多人团队开发中经常为了保持代码的统一规范对项目进行 eslint 配置,本章主要就是介绍该配置过程:

package.json 中安装依赖如下:

1
2
3
4
5
6
7
8
9
10
{
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.32.0",
"@typescript-eslint/parser": "^4.32.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"prettier": "^2.4.1"
}
}

新增 .prettierrc.js 的配置如下:

1
2
3
4
5
6
7
8
module.exports = {
semi: false,
trailingComma: 'all',
singleQuote: true,
printWidth: 90,
tabWidth: 4,
useTabs: false,
}

新增 .eslintrc.js 的配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
module.exports = {
env: {
es2021: true,
browser: true,
node: true,
es6: true,
jest: true,
},
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['@typescript-eslint', 'prettier'],
rules: {
'require-atomic-updates': 'warn',
'no-console': 'warn',
'react/display-name': 'off',
'react/prop-types': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'prettier/prettier': 'error',
// "@typescript-eslint/interface-name-prefix": "warn",
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/no-empty-function': 'warn',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-empty-interface': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
}

开启保存时自动格式化

.vsocde 中的 settings.json 中增加:

1
2
3
4
5
6
{
"typescript.tsdk": "node_modules/typescript/lib",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}