前端h5项目统一代码风格配置(eslint + stylelint + prettier + husky + lint-staged)

本文主要是介绍前端h5项目统一代码风格配置(eslint + stylelint + prettier + husky + lint-staged),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、概述

这里的统一代码风格包括编辑器基本配置、代码校验、格式化工具、git提交前校验等,强烈建议配置下,特别是eslint起初可能不习惯,其实三五天时间就适应了,能帮助避免很多低级错误,另外对于团队开发也很重要。
先介绍下这里需要用到的几个工具:

  • editorconfig 统一编辑器基本配置
  • eslint js校验工具。
  • stylelint css校验工具,也支持less等css预处理器。
  • prettier 代码格式化工具,主要用于格式化html或jsx部分的代码,一般写代码习惯好就不需要这个,可配置项很少,有点鸡肋吧。
  • husky 是一个gitHook工具,可以配置git的一些钩子,本文主要用来配置 commit 钩子。
  • lint-staged 是一个在git暂存文件上运行lint校验的工具,配合husky配置commit钩子,用于git commit前的强制校验。

二、editorConfig

这个工具是用于统一不同编辑器和不同操作系统等环境的项目配置。

  • 对于vscode,需要安装扩展:EditorConfig for VS Code
  • 然后项目根目录添加文件 .editorconfig,编写以下配置:
root = true[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = crlf
insert_final_newline = true
trim_trailing_whitespace = true[*.md]
insert_final_newline = false
trim_trailing_whitespace = false

三、eslint

(本文版本v7.32.0)
js校验必备,注意eslint只针对js或ts做校验,按以下方式配置完后可做到保存时自动校验并修复。

1、配置vscode

  • 安装vscode扩展eslint
  • 设置文件 settings.json 里添加配置
"eslint.validate": ["html","vue","javascript","javascriptreact", "typescript","typescriptreact"
],
"editor.codeActionsOnSave": {"source.fixAll.eslint": true,"source.fixAll.stylelint": true
},

2、项目基础配置

推荐使用standard配置规范。
插件:eslint-config-standard

(1)安装依赖

安装 eslint + standard 规范依赖:

npm i -D eslint eslint-config-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node

(2)添加配置文件

  • 项目根目录添加eslint配置文件 .eslintrc.js
module.exports = {root: true,env: {browser: true,node: true},extends: ['standard','eslint:recommended',],parserOptions: {ecmaFeatures: {jsx: true,},ecmaVersion: 2020,sourceType: 'module'},globals: {},ignorePatterns: ['dist','build','scripts','config','*.html',],rules: {'no-console': 'off','no-debugger': 'off','camelcase': 'off','comma-dangle': 'off','handle-callback-err': 'off','no-unused-vars': 'off','quote-props': 'off','no-extra-semi': 'off','prefer-promise-reject-errors': 'off','prefer-const': 'off',}
}

3、vue项目

在上述目录 2、项目基础配置 的基础上,额外配置vue语法校验。
插件:eslint-plugin-vue

(1)额外安装依赖

npm i -D eslint-plugin-vue

(2)修改配置文件

  • 修改eslint配置文件 .eslintrc.js
module.exports = {...,extends: [...,'plugin:vue/vue3-essential', // vue3适用// 'plugin:vue/essential', // vue2适用],...,
}

4、react项目

在上述目录 2、项目基础配置 的基础上,额外配置react语法校验。
插件:eslint-plugin-react

(1)安装依赖

npm i -D eslint-plugin-react eslint-plugin-react-hooks

(2)修改配置文件

  • 修改eslint配置文件 .eslintrc.js
module.exports = {...,extends: [...,'plugin:react/recommended','plugin:react-hooks/recommended',],settings: {react: {version: 'detect'}},...,rules: {...,'react/display-name': 'off','react/react-in-jsx-scope': 'off','react-hooks/exhaustive-deps': 'off',}
}

5、ts校验

如果项目使用ts代码,需要额外配置ts相关的校验。

首先需要按上述的eslint配置教程配置好eslint,然后再继续:

(1)vue

插件:@vue/eslint-config-typescript

  • 安装依赖:
npm i D typescript @vue/eslint-config-typescript
  • 修改eslint配置文件 .eslintrc.js
module.exports = {...,extends: [...,'@vue/eslint-config-typescript/recommended'],...,
}

(2)react

插件集:@typescript-eslint

  • 安装依赖:
npm i D typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin
  • 修改eslint配置文件 .eslintrc.js
module.exports = {...,extends: [...,'plugin:@typescript-eslint/recommended'],parser: '@typescript-eslint/parser',plugins: ['@typescript-eslint',],...,rules: {...,"no-use-before-define": "off","@typescript-eslint/no-use-before-define": ['error', { 'functions': false, }],'@typescript-eslint/triple-slash-reference': 'off','@typescript-eslint/no-var-requires': 'off','@typescript-eslint/no-explicit-any': 'off','@typescript-eslint/no-unused-vars': 'off',}
}

6、webpack插件

对于webpack项目,eslint-webpack-plugin可以帮助在webpack编译或热更新时实时校验代码并作出错误提示。(一般官方脚手架里已经集成好了)。

  • 安装依赖:
npm i eslint-webpack-plugin -D
  • 在webpack的plugins配置文件(例如webpack.base.conf.js)里添加:
const ESLintPlugin = require('eslint-webpack-plugin');module.exports = {// ...plugins: [...new ESLintPlugin({extensions: ['vue', 'html', 'js', 'ts', 'jsx', 'tsx']})],// ...
}

四、stylelint

(本文版本v14.2.0,)
stylelint 针对 css 或 css 预处理器的代码做校验。

下面将以配置 css 和 less 的校验为例。

1、配置vscode

  • 安装vscode扩展stylelint
  • 设置文件 settings.json里添加配置
"editor.codeActionsOnSave": {"source.fixAll.eslint": true,"source.fixAll.stylelint": true
},
"css.validate": false,
"less.validate": false,
"scss.validate": false,
"stylelint.validate": ["css","less","postcss"
],
  • (可选)如需要自定义编辑器默认配置,通过settings.json里配置stylelint.configOverrides的rules实现:
// 这里的配置优先级低于.stylelintrc.js文件,适合用作编辑器的默认配置
"stylelint.configOverrides": {"rules": {// 示例,配置支持小程序rpx单位"unit-no-unknown": [true,{ "ignoreUnits": ["rpx"] }],},// 示例,配置忽略列表文件"ignoreFiles": ["node_modules/**/*","dist/**/*","**/*.js","**/*.jsx","**/*.tsx","**/*.ts"]
},

2、安装依赖包

npm i stylelint stylelint-config-standard postcss-less -D

3、添加项目配置文件

  • 项目根目录添加 .stylelintrc.js
module.exports = {extends: ['stylelint-config-standard'],overrides: [{'files': ['**/*.less'],'customSyntax': 'postcss-less'}],rules: {'rule-empty-line-before': null,'font-family-no-missing-generic-family-keyword': null,'no-descending-specificity': null,'color-hex-case': null,'no-empty-source': null,'block-no-empty': null,"selector-pseudo-class-no-unknown": [true,{ "ignorePseudoClasses": ["global"] }],'string-quotes': null,'selector-class-pattern': null,'value-no-vendor-prefix': null,'property-no-vendor-prefix': null,'color-function-notation': null,'alpha-value-notation': null},ignoreFiles: ['node_modules/**/*','public/**/*','dist/**/*','build/**/*','**/*.js','**/*.jsx','**/*.ts','**/*.tsx'],
}

ps:关于stylelint-webpack-plugin插件,功能类似于eslint的eslint-webpack-plugin,但经实测会影响webpack热更新速度,不建议使用。

五、prettier

prettier 是一套代码格式规范,一般用作格式化工具。而在项目中,js交给eslint,css交给stylelint,这个主要就用于html或jsx部分的格式化。

但是prettier配置项太少,和eslint的格式效果也会有冲突(eslint-config-prettier会以prettier优先),个人建议可以配置好用于需要时手动格式化功能,但不建议配置prettier的自动校验及格式化(例如lint-staged)。

1、添加项目配置

  • 项目 package.json 里添加 prettier 字段:
"prettier": {"eslintIntegration": true,"stylelintIntegration": true,"tabWidth": 2,"singleQuote": true,"semi": false,"printWidth": 100
}

2、配置vscode

  • vscode添加扩展:Prettier
  • 设置文件 settings.json里添加配置
"[html]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[less]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[vue]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {"editor.defaultFormatter": "esbenp.prettier-vscode"
},"prettier.semi": false,
"prettier.singleQuote": true,
"prettier.printWidth": 100,"vetur.format.defaultFormatter.html": "prettier",
"vetur.format.defaultFormatterOptions": {"prettier": {"eslintIntegration": true,"stylelintIntegration": true}
},

六、husky + lint-staged

(版本:husky7.0.4 + lint-staged12.1.5)
只是单纯引入校验如果不强制要求就等于没做,总会有人偷懒,所以还是要约束一下。

  • husky用于git执行钩子前做校验,
  • lint-staged用于只校验git暂存区的文件。
  • 这里要实现的功能是在git commit命令运行时先校验lint(包括eslint和stylelint)是否通过,未通过则不予commit。

注:husky v7 版本的配置方式已经和之前v4相比已经完全改变,官方文档。
lint-staged v12 版本的配置同样也跟着husky变了,官方文档。

(1)安装依赖:

npm i husky lint-staged -D

(2)package.json的scripts里添加命令:

"prepare": "husky install"

(3)npm run prepare运行命令。

(会自动在项目根目录创建.husky文件夹)

(4)然后运行命令npx husky add .husky/pre-commit "npx lint-staged"

(会自动在.husky目录添加pre-commit文件,并添加了相应的git hooks文件,pre-commit文件里也自动写入了npx lint-staged内容,意思就是git commit的时候自动执行npx lint-staged命令来校验,接下来需要配置lint-staged)

(5)package.json里添加:

"lint-staged": {"*.{js,jsx,ts,tsx}": "eslint --cache --cache-location .husky/_/.eslintcache --fix","*.{css,less}": "stylelint --custom-syntax postcss-less --fix"
},

大功告成。

  • 第(5)步我这里是同时配置了eslint和stylelint的校验,不需要的可以移除。
  • 关于团队合作方面,其实在执行npm i的时候会自动执行npm run prepare命令,并根据.husky目录的钩子文件自动生成相关的其他文件,所以,只要不删prepare命令,不忽略.husky文件夹,团队配置一致性就没有问题。
  • 需要注意,强制校验相关的控制文件都是在.git文件夹内,如果不小心删除了这个文件夹,需要重新安装依赖包(husky)后强制校验才能生效。

这篇关于前端h5项目统一代码风格配置(eslint + stylelint + prettier + husky + lint-staged)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/960065

相关文章

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

Linux中SSH服务配置的全面指南

《Linux中SSH服务配置的全面指南》作为网络安全工程师,SSH(SecureShell)服务的安全配置是我们日常工作中不可忽视的重要环节,本文将从基础配置到高级安全加固,全面解析SSH服务的各项参... 目录概述基础配置详解端口与监听设置主机密钥配置认证机制强化禁用密码认证禁止root直接登录实现双因素

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

如何在Spring Boot项目中集成MQTT协议

《如何在SpringBoot项目中集成MQTT协议》本文介绍在SpringBoot中集成MQTT的步骤,包括安装Broker、添加EclipsePaho依赖、配置连接参数、实现消息发布订阅、测试接口... 目录1. 准备工作2. 引入依赖3. 配置MQTT连接4. 创建MQTT配置类5. 实现消息发布与订阅

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

springboot项目打jar制作成镜像并指定配置文件位置方式

《springboot项目打jar制作成镜像并指定配置文件位置方式》:本文主要介绍springboot项目打jar制作成镜像并指定配置文件位置方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录一、上传jar到服务器二、编写dockerfile三、新建对应配置文件所存放的数据卷目录四、将配置文

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Linux如何快速检查服务器的硬件配置和性能指标

《Linux如何快速检查服务器的硬件配置和性能指标》在运维和开发工作中,我们经常需要快速检查Linux服务器的硬件配置和性能指标,本文将以CentOS为例,介绍如何通过命令行快速获取这些关键信息,... 目录引言一、查询CPU核心数编程(几C?)1. 使用 nproc(最简单)2. 使用 lscpu(详细信

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)