React+Typescript+Prettier+ESLint 项目初始化

项目初始化

Posted by Yinode on Monday, July 19, 2021

TOC

React项目初始化 TypeScript + ESLint + Prettier自动格式化

新建项目

需要提前安装create-react-app命令,不做赘述

npx create-react-app your-app-name --template typescript
cd your-app-name

添加并初始化eslint

yarn global add eslint
eslint --init

如果出现找不到eslint这个命令 可以尝试

./node_modules/.bin/eslint --init

按顺序选择如下选项

✔ How would you like to use ESLint? · style (第三个选项)
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · react
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · airbnb
✔ What format do you want your config file to be in? · JSON

接下来会进行简单的依赖安装 当然你手动用yarn也行

进一步安装TypeScript相关的ESLint插件

yarn add --dev eslint-plugin-react @typescript-eslint/eslint-plugin@latest eslint-config-airbnb@latest eslint eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react-hooks  @typescript-eslint/parser@latest

编辑.eslintrc.json

{
	"env": {
		"browser": true,
		"es2021": true
	},
	"extends": ["plugin:react/recommended", "airbnb", "prettier"],
	"parser": "@typescript-eslint/parser",
	"parserOptions": {
		"ecmaFeatures": {
			"jsx": true
		},
		"ecmaVersion": 12,
		"sourceType": "module"
	},
	"plugins": ["react", "@typescript-eslint"],
	"rules": {
		"react/react-in-jsx-scope": "off",
		"no-use-before-define": "off",
		"@typescript-eslint/no-use-before-define": ["error"],
		"react/jsx-filename-extension": [
			1,
			{ "extensions": [".js", ".jsx", ".ts", ".tsx"] }
		],
		"import/extensions": "off"
	},
	"settings": {
		"import/resolver": {
			"node": {
				"extensions": [".js", ".jsx", ".ts", ".tsx"]
			}
		}
	}
}

VSCode增加TS格式化工具

// settings.json vs-code

// TS的默认格式化工具为Prettier
"[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },

// 启动保存自动ESLint修复
"editor.codeActionsOnSave": {
     "source.fixAll.eslint": true
 },

按下prettier对应快捷键即可自动格式化代码

最终成品

zhangzhengyi12/react-with-typescript-prettier-eslint-template