使用Typescript, ESLint, Prettier来搭建React开发环境

前端新手……………….,先安装create-react-app

使用Typescript安装

1
yarn create react-app my-test-ts --typescript

安装ESLint, Prettier

1
2
yarn add eslint eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin --dev
yarn add prettier eslint-plugin-prettier eslint-config-prettier --dev

创建 .eslintrc.js 文件,可以加入rules的规则,但是在加入之前一定要组内讨论一下。

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
31
32
33
34
35
36
37
module.exports = {
// 指定 ESLint parser
parser: '@typescript-eslint/parser',
extends: [
// 使用 @eslint-plugin-react 中推荐的规则
'plugin:react/recommended',
// 使用 @typescript-eslint/eslint-plugin 中推荐的规则
'plugin:@typescript-eslint/recommended',
// 使用 eslint-config-prettier 来禁止 @typescript-eslint/eslint-plugin 中那些和 prettier 冲突的规则
'prettier/@typescript-eslint',
// 使用 eslint-plugin-prettier 来将 prettier 错误作为 ESLint 错误显示
// 确保下面这行配置是这个数组里的最后一行配置
'plugin:prettier/recommended',
],
parserOptions: {
ecmaVersion: 2018, // 允许解析现代 es 特性
sourceType: 'module', // 允许使用 imports
ecmaFeatures: {
jsx: true, // 允许解析 jsx
},
},
rules: {
'react/display-name': 'off',
'react/prop-types': 'off',
'import/no-unresolved': 'off',
'react/jsx-filename-extension': [1, { "extensions": [".ts", ".tsx"] }],
'no-undef': 'off',
// 类名与接口名必须为驼峰式
'@typescript-eslint/class-name-casing': 'error',
},
settings: {
react: {
// Tells eslint-plugin-react to automatically detect the version of React to use
version: 'detect',
},
},
}

创建 .prettierrc.js 文件

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

安装eslint-config-airbnb

1
npx install-peerdeps --dev eslint-config-airbnb

添加 “extends”: “airbnb” 到 .eslintrc

VsCode配置

setting.json配置

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
{
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",
"javascriptreact",
{ "language": "typescript", "autoFix": true },
{ "language": "typescriptreact", "autoFix": true }
],
"editor.formatOnSave": true,
"[javascript]": {
"editor.formatOnSave": false
},
"[javascriptreact]": {
"editor.formatOnSave": false
},
"[typescript]": {
"editor.formatOnSave": false
},
"[typescriptreact]": {
"editor.formatOnSave": false
},
"javascript.updateImportsOnFileMove.enabled": "always",
"typescript.updateImportsOnFileMove.enabled": "always"
}