前端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

相关文章

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖

利用Python调试串口的示例代码

《利用Python调试串口的示例代码》在嵌入式开发、物联网设备调试过程中,串口通信是最基础的调试手段本文将带你用Python+ttkbootstrap打造一款高颜值、多功能的串口调试助手,需要的可以了... 目录概述:为什么需要专业的串口调试工具项目架构设计1.1 技术栈选型1.2 关键类说明1.3 线程模

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

解决Maven项目idea找不到本地仓库jar包问题以及使用mvn install:install-file

《解决Maven项目idea找不到本地仓库jar包问题以及使用mvninstall:install-file》:本文主要介绍解决Maven项目idea找不到本地仓库jar包问题以及使用mvnin... 目录Maven项目idea找不到本地仓库jar包以及使用mvn install:install-file基

如何为Yarn配置国内源的详细教程

《如何为Yarn配置国内源的详细教程》在使用Yarn进行项目开发时,由于网络原因,直接使用官方源可能会导致下载速度慢或连接失败,配置国内源可以显著提高包的下载速度和稳定性,本文将详细介绍如何为Yarn... 目录一、查询当前使用的镜像源二、设置国内源1. 设置为淘宝镜像源2. 设置为其他国内源三、还原为官方

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生成自签名证书将