前端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的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

CentOS7更改默认SSH端口与配置指南

《CentOS7更改默认SSH端口与配置指南》SSH是Linux服务器远程管理的核心工具,其默认监听端口为22,由于端口22众所周知,这也使得服务器容易受到自动化扫描和暴力破解攻击,本文将系统性地介绍... 目录引言为什么要更改 SSH 默认端口?步骤详解:如何更改 Centos 7 的 SSH 默认端口1

springboot项目如何开启https服务

《springboot项目如何开启https服务》:本文主要介绍springboot项目如何开启https服务方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录springboot项目开启https服务1. 生成SSL证书密钥库使用keytool生成自签名证书将

Maven的使用和配置国内源的保姆级教程

《Maven的使用和配置国内源的保姆级教程》Maven是⼀个项目管理工具,基于POM(ProjectObjectModel,项目对象模型)的概念,Maven可以通过一小段描述信息来管理项目的构建,报告... 目录1. 什么是Maven?2.创建⼀个Maven项目3.Maven 核心功能4.使用Maven H

SpringBoot多数据源配置完整指南

《SpringBoot多数据源配置完整指南》在复杂的企业应用中,经常需要连接多个数据库,SpringBoot提供了灵活的多数据源配置方式,以下是详细的实现方案,需要的朋友可以参考下... 目录一、基础多数据源配置1. 添加依赖2. 配置多个数据源3. 配置数据源Bean二、JPA多数据源配置1. 配置主数据

HTML5中的Microdata与历史记录管理详解

《HTML5中的Microdata与历史记录管理详解》Microdata作为HTML5新增的一个特性,它允许开发者在HTML文档中添加更多的语义信息,以便于搜索引擎和浏览器更好地理解页面内容,本文将探... 目录html5中的Mijscrodata与历史记录管理背景简介html5中的Microdata使用M

html5的响应式布局的方法示例详解

《html5的响应式布局的方法示例详解》:本文主要介绍了HTML5中使用媒体查询和Flexbox进行响应式布局的方法,简要介绍了CSSGrid布局的基础知识和如何实现自动换行的网格布局,详细内容请阅读本文,希望能对你有所帮助... 一 使用媒体查询响应式布局        使用的参数@media这是常用的

HTML5表格语法格式详解

《HTML5表格语法格式详解》在HTML语法中,表格主要通过table、tr和td3个标签构成,本文通过实例代码讲解HTML5表格语法格式,感兴趣的朋友一起看看吧... 目录一、表格1.表格语法格式2.表格属性 3.例子二、不规则表格1.跨行2.跨列3.例子一、表格在html语法中,表格主要通过< tab

Spring 基于XML配置 bean管理 Bean-IOC的方法

《Spring基于XML配置bean管理Bean-IOC的方法》:本文主要介绍Spring基于XML配置bean管理Bean-IOC的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录一. spring学习的核心内容二. 基于 XML 配置 bean1. 通过类型来获取 bean2. 通过

将Java项目提交到云服务器的流程步骤

《将Java项目提交到云服务器的流程步骤》所谓将项目提交到云服务器即将你的项目打成一个jar包然后提交到云服务器即可,因此我们需要准备服务器环境为:Linux+JDK+MariDB(MySQL)+Gi... 目录1. 安装 jdk1.1 查看 jdk 版本1.2 下载 jdk2. 安装 mariadb(my