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

相关文章

mybatis映射器配置小结

《mybatis映射器配置小结》本文详解MyBatis映射器配置,重点讲解字段映射的三种解决方案(别名、自动驼峰映射、resultMap),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定... 目录select中字段的映射问题使用SQL语句中的别名功能使用mapUnderscoreToCame

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资

MySQL8 密码强度评估与配置详解

《MySQL8密码强度评估与配置详解》MySQL8默认启用密码强度插件,实施MEDIUM策略(长度8、含数字/字母/特殊字符),支持动态调整与配置文件设置,推荐使用STRONG策略并定期更新密码以提... 目录一、mysql 8 密码强度评估机制1.核心插件:validate_password2.密码策略级