前端规范工程-2:JS代码规范(Prettier + ESLint)

Prettier 和 ESLint 是两个在现代 JavaScript 开发中广泛使用的工具,它们结合起来可以提供以下作用和优势:

  1. 代码格式化和风格统一

    • Prettier 是一个代码格式化工具,能够自动化地处理代码的缩进、空格、换行等格式问题,确保整个项目的代码风格一致。
    • 在团队开发中,Prettier 可以消除因个人习惯或编辑器设置不同而导致的代码格式差异,提高代码的可读性和维护性。
  2. 代码质量和规范检查

    • ESLint 是一个 JavaScript 和 TypeScript 代码的静态分析工具,用于发现和修复代码中的问题,例如语法错误、不符合规范的代码等。
    • 通过配置规则,ESLint 可以强制执行团队约定的代码风格、最佳实践和安全性规则,帮助团队编写更高质量、更一致的代码。
  3. 结合使用的优势

    • 格式化和规范检查的一体化:Prettier 负责格式化,ESLint 负责规范检查。结合使用可以确保代码不仅格式良好,还符合团队的代码规范和最佳实践。
    • 自动化和持续集成:可以将 Prettier 和 ESLint 集成到 CI/CD 流水线中,在每次提交或部署前自动运行,提早发现和修复潜在问题。
  4. 可定制性和配置

    • Prettier 和 ESLint 都支持广泛的配置选项和插件系统,可以根据团队的需求和偏好进行定制和扩展。
    • 通过共享和维护一个统一的配置文件(如 .prettierrc.cjs.eslintrc.cjs),可以确保整个团队在开发过程中遵循相同的代码风格和规范。

目录

代码格式化配置(Prettier)

1、安装插件

2、下载 prettier 相关依赖

js 复制代码
pnpm i prettier -D

3、配置 Prettier(.prettierrc.cjs)

Prettier 默认优先读取项目中的配置文件,以确定代码格式化的规则。具体来说,Prettier 会按照以下优先级查找配置:

  • package.json文件中的 prettier 关键字
  • .prettierrc 文件(以 JSONYAML 编写的)
  • .prettierrc.json.prettierrc.yml.prettierrc.yaml.prettierrc.json5 文件
  • .prettierrc.jsprettier.config.js 文件,使用 export defaultmodule.exports 导出对象 (取决于 package.json 中的 type 值 )。
  • .prettierrc.mjsprettier.config.mjs 文件,使用 export default 导出对象。
  • .prettierrc.cjsprettier.config.cjs 文件,使用 module.exports 导出对象。
  • .prettierrc.toml 文件。
js 复制代码
// @see: https://www.prettier.cn
module.exports = {
	// 指定最大换行长度
	printWidth: 120,
	// 缩进制表符宽度 | 空格数
	tabWidth: 2,
	// 使用制表符而不是空格缩进行 (true:制表符,false:空格)
	useTabs: false,
	// 结尾不用分号 (true:有,false:没有)
	semi: true,
	// 使用单引号 (true:单引号,false:双引号)
	singleQuote: false,
	// 在对象字面量中决定是否将属性名用引号括起来 可选值 "<as-needed|consistent|preserve>"
	quoteProps: "as-needed",
	// 在JSX中使用单引号而不是双引号 (true:单引号,false:双引号)
	jsxSingleQuote: false,
	// 多行时尽可能打印尾随逗号 可选值"<none|es5|all>"
	trailingComma: "none",
	// 在对象,数组括号与文字之间加空格 "{ foo: bar }" (true:有,false:没有)
	bracketSpacing: true,
	// 将 > 多行元素放在最后一行的末尾,而不是单独放在下一行 (true:放末尾,false:单独一行)
	bracketSameLine: false,
	// (x) => {} 箭头函数参数只有一个时是否要有小括号 (avoid:省略括号,always:不省略括号)
	arrowParens: "avoid",
	// 指定要使用的解析器,不需要写文件开头的 @prettier
	requirePragma: false,
	// 可以在文件顶部插入一个特殊标记,指定该文件已使用 Prettier 格式化
	insertPragma: false,
	// 用于控制文本是否应该被换行以及如何进行换行
	proseWrap: "preserve",
	// 在html中空格是否是敏感的 "css" - 遵守 CSS 显示属性的默认值, "strict" - 空格被认为是敏感的 ,"ignore" - 空格被认为是不敏感的
	htmlWhitespaceSensitivity: "css",
	// 控制在 Vue 单文件组件中 <script> 和 <style> 标签内的代码缩进方式
	vueIndentScriptAndStyle: false,
	// 换行符使用 lf 结尾是 可选值 "<auto|lf|crlf|cr>"
	endOfLine: "auto",
	// 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码 (rangeStart:开始,rangeEnd:结束)
	rangeStart: 0,
	rangeEnd: Infinity,
};

4、Prettier忽略文件(.prettierignore)

js 复制代码
/dist/*
.local
/node_modules/**

**/*.svg
**/*.sh

/public/*

5、package.json 配置命令脚本

js 复制代码
"scripts":{
    //......其他省略
    "lint:prettier": "prettier --write \"src/**/*.{js,ts,json,tsx,css,less,scss,vue,html,md}\"",
}

运行命令 pnpm run lint:prettier,比如有如下的js代码:

执行命令之后:

代码规范工具(ESLint)

1、安装插件 ESLint

2、项目下载依赖

bash 复制代码
pnpm i eslint eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue @typescript-eslint/eslint-plugin @typescript-eslint/parser -D
依赖 作用描述
eslint ESLint 核心库
eslint-config-prettier 关掉所有和 Prettier 冲突的 ESLint 的配置
eslint-plugin-prettier 将 Prettier 的 rules 以插件的形式加入到 ESLint 里面
eslint-plugin-vue 为 Vue 使用 ESlint 的插件
@typescript-eslint/eslint-plugin ESLint 插件,包含了各类定义好的检测 TypeScript 代码的规范
@typescript-eslint/parser ESLint 的解析器,用于解析 TypeScript,从而检查和规范 TypeScript 代码

3、配置 ESLint(.eslintrc.cjs)

js 复制代码
// @see: http://eslint.cn
module.exports = {
	root: true,
	env: {
		browser: true,
		node: true,
		es6: true,
	},
	// 指定如何解析语法
	parser: "vue-eslint-parser",
	// 优先级低于 parse 的语法解析配置
	parserOptions: {
		parser: "@typescript-eslint/parser",
		ecmaVersion: 2020,
		sourceType: "module",
		jsxPragma: "React",
		ecmaFeatures: {
			jsx: true,
		},
	},
	// 继承某些已有的规则
	extends: [
		"plugin:vue/vue3-recommended",
		"plugin:@typescript-eslint/recommended",
		"plugin:prettier/recommended",
	],
	/**
	 * "off" 或 0    ==>  关闭规则
	 * "warn" 或 1   ==>  打开的规则作为警告(不影响代码执行)
	 * "error" 或 2  ==>  规则作为一个错误(代码不能执行,界面报错)
	 */
	rules: {
		// eslint (http://eslint.cn/docs/rules)
		"no-var": "error", // 要求使用 let 或 const 而不是 var
		"no-multiple-empty-lines": ["error", { max: 1 }], // 不允许多个空行
		"prefer-const": "off", // 使用 let 关键字声明但在初始分配后从未重新分配的变量,要求使用 const
		"no-use-before-define": "off", // 禁止在 函数/类/变量 定义之前使用它们
		"no-irregular-whitespace": "off", // 禁止不规则的空白

		// typeScript (https://typescript-eslint.io/rules)
		"@typescript-eslint/no-unused-vars": "error", // 禁止定义未使用的变量
		"@typescript-eslint/prefer-ts-expect-error": "error", // 禁止使用 @ts-ignore
		"@typescript-eslint/no-inferrable-types": "off", // 可以轻松推断的显式类型可能会增加不必要的冗长
		"@typescript-eslint/no-namespace": "off", // 禁止使用自定义 TypeScript 模块和命名空间。
		"@typescript-eslint/no-explicit-any": "off", // 禁止使用 any 类型
		"@typescript-eslint/ban-types": "off", // 禁止使用特定类型
		"@typescript-eslint/explicit-function-return-type": "off", // 不允许对初始化为数字、字符串或布尔值的变量或参数进行显式类型声明
		"@typescript-eslint/no-var-requires": "off", // 不允许在 import 语句中使用 require 语句
		"@typescript-eslint/no-empty-function": "off", // 禁止空函数
		"@typescript-eslint/no-use-before-define": "off", // 禁止在变量定义之前使用它们
		"@typescript-eslint/ban-ts-comment": "off", // 禁止 @ts-<directive> 使用注释或要求在指令后进行描述
		"@typescript-eslint/no-non-null-assertion": "off", // 不允许使用后缀运算符的非空断言(!)
		"@typescript-eslint/explicit-module-boundary-types": "off", // 要求导出函数和类的公共类方法的显式返回和参数类型

		// vue (https://eslint.vuejs.org/rules)
		"vue/script-setup-uses-vars": "error", // 防止<script setup>使用的变量<template>被标记为未使用,此规则仅在启用该no-unused-vars规则时有效。
		"vue/v-slot-style": "error", // 强制执行 v-slot 指令样式
		"vue/no-mutating-props": "off", // 不允许组件 prop的改变
		"vue/no-v-html": "off", // 禁止使用 v-html
		"vue/custom-event-name-casing": "off", // 为自定义事件名称强制使用特定大小写
		"vue/attributes-order": "off", // vue api使用顺序,强制执行属性顺序
		"vue/one-component-per-file": "off", // 强制每个组件都应该在自己的文件中
		"vue/html-closing-bracket-newline": "off", // 在标签的右括号之前要求或禁止换行
		"vue/max-attributes-per-line": "off", // 强制每行的最大属性数
		"vue/multiline-html-element-content-newline": "off", // 在多行元素的内容之前和之后需要换行符
		"vue/singleline-html-element-content-newline": "off", // 在单行元素的内容之前和之后需要换行符
		"vue/attribute-hyphenation": "off", // 对模板中的自定义组件强制执行属性命名样式
		"vue/require-default-prop": "off", // 此规则要求为每个 prop 为必填时,必须提供默认值
		"vue/multi-word-component-names": "off", // 要求组件名称始终为 "-" 链接的单词
	},
};

注意: 上面ESLint并不是要全部使用,只是罗列了常见的配置,具体使用的时候请根据自己项目的情况进行配置

4、ESlint忽略文件(.eslintignore)

js 复制代码
*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
/src/mock/*

5、package.json配置命令脚本

js 复制代码
"scripts":{
    //......其他省略
    "lint:eslint": "eslint --fix --ext .js,.ts,.vue ./src",
}

对以下代码进行处理

命令 npm run lint:eslint运行之后

提示您有2处有赋值但从未使用的变量,您需要手动删除或注释。

相关推荐
觉醒法师22 分钟前
VSCode开发Vue3+TS项目中遇到各种波浪线(诊断信息)
前端·ide·vue.js·vscode·typescript·编辑器
一丝晨光1 小时前
void类型
java·开发语言·javascript·c++·c#·go·c
UvwxyZ6661 小时前
web开发(1)-基础
前端
大得3693 小时前
vue到出excel
javascript·vue.js·excel
半吊子伯爵5 小时前
试用Foxit PDF: 在网页中单页展示PDF
前端·javascript·foxit pdf
徐_三岁6 小时前
Vue3实现mqtt的订阅与发布
前端
itas1097 小时前
Electron获取nodejs和chrome版本信息
javascript·chrome·electron·nodejs·node
qq_544329177 小时前
从0学习React(5)---通过例子体会setState
前端·学习·react.js
xcLeigh8 小时前
HTML5实现好看的唐朝服饰网站模板源码2
前端·html·html5