【react进阶】create-react-app的项目工程格式化和eslint校验配置

在团队合作中,规范必须是要约束的,每个人都有自己的习惯,需要达成共识,规范书写格式,不能各自按各自的方式来,乱套了就不方便项目代码的管理。

确保node版本是18.18以上,配合最新版的eslint的校验有效,非ts项目的

package.json

json 复制代码
{
	"name": "react18_app2",
	"version": "0.1.0",
	"private": true,
	"dependencies": {
		"@testing-library/jest-dom": "^5.17.0",
		"@testing-library/react": "^13.4.0",
		"@testing-library/user-event": "^13.5.0",
		"husky": "^9.1.7",
		"prettier": "^3.4.2",
		"react": "^18.0.0",
		"react-dom": "^18.0.0",
		"react-scripts": "5.0.1",
		"sass": "^1.83.1",
		"web-vitals": "^2.1.4"
	},
	"scripts": {
		"start": "craco start ",
		"build": "craco build",
		"test": "craco  test",
		"eject": "react-scripts eject",
		"lint": "eslint src  -c eslint.config.mjs --fix",
		"prepare": "husky",
		"lint:lint-staged": "lint-staged"
	},
	"browserslist": {
		"production": [
			">0.2%",
			"not dead",
			"not op_mini all"
		],
		"development": [
			"last 1 chrome version",
			"last 1 firefox version",
			"last 1 safari version"
		]
	},
	"devDependencies": {
		"@craco/craco": "^7.1.0",
		"lint-staged": "^15.3.0"
	},
	"lint-staged": {
		"src/**/*.{ts,tsx,js,jsx}": [
			"prettier --write",
			"eslint -c eslint.config.mjs --fix",
			"git add"
		]
	}
}

vscode插件安装

json 复制代码
{
	"prettier.singleQuote": true,
	"prettier.jsxSingleQuote": true,
	"prettier.semi": false,
	"prettier.useTabs": true,
	"prettier.tabWidth": 4,
	"prettier.printWidth": 120,
	"prettier.bracketSameLine": true,
	"editor.defaultFormatter": "esbenp.prettier-vscode",
	"editor.codeActionsOnSave": {
		"source.fixAll.eslint": "always"
	},
	"editor.formatOnSave": true,
	"eslint.format.enable": false
}

然后这样,就能保证代码在保存的时候进行美化了。注意:eslint是用来限制代码规范的,prettier是用来美化代码的格式。

eslint的配置

bash 复制代码
npm init @eslint/config@latest

生成了这样一个默认的配置文件。

添加自定义配置规则

js 复制代码
import globals from 'globals'
import pluginJs from '@eslint/js'
import pluginReact from 'eslint-plugin-react'

/** @type {import('eslint').Linter.Config[]} */
export default [
	{ files: ['**/*.{js,mjs,cjs,jsx}'] },
	{ languageOptions: { globals: globals.browser } },
	pluginJs.configs.recommended,
	pluginReact.configs.flat.recommended,
	{
		rules: {
			'react/prop-types': 'off',
			'react/react-in-jsx-scope': 'off',
			'no-undef': 'off',
		},
	},
]
  • 安装husky,和lint-stage

添加配置项


测试效果

  • 目标是,写完代码后,保存双引号改为单引号,去掉末尾分号
  • commit提交后校验不规范的代码

报错且提交未成功,是因为开启了no-unused-vars,默认是true,关闭这个配置即可

再次commit

提交成功

相关推荐
longze_71 小时前
Vue中:deep()和 ::v-deep选择器的区别
前端·javascript·vue.js
太阳伞下的阿呆4 小时前
本地环境vue与springboot联调
前端·vue.js·spring boot
阳光是sunny4 小时前
走进微前端(1)手写single-spa核心原理
前端·javascript·vue.js
烛阴5 小时前
Ceil -- 从平滑到阶梯
前端·webgl
90后的晨仔5 小时前
🔍Vue 模板引用(Template Refs)全解析:当你必须操作 DOM 时
前端·vue.js
90后的晨仔5 小时前
👂 Vue 侦听器(watch)详解:监听数据的变化
前端·vue.js
90后的晨仔6 小时前
深入浅出 Vue 的 computed:不仅仅是“计算属性”那么简单!
前端·vue.js
Nan_Shu_6146 小时前
学习:入门uniapp Vue3组合式API版本(17)
前端·vue.js·学习·uni-app
止观止7 小时前
Remix框架:高性能React全栈开发实战
前端·react.js·前端框架·remix
萌萌哒草头将军7 小时前
🚀🚀🚀 深入探索 Node.js v22.18.0 新特性;默认支持运行 ts 文件了!
前端·typescript·node.js