前端项目如何配置开发校验规范

发布于:2025-06-30 ⋅ 阅读:(19) ⋅ 点赞:(0)

本文章算是自己项目初始化搭建的一个步骤备份,讲述了一个前端项目完成的开发规范校验步骤,从eslint、prettier、commit lint等过程

校验规范 eslint

  1. 安装
pnpm i eslint -D -w
  1. 初始化
npx eslint --init

npx eslint --init 执行选择

✔ What do you want to lint? · javascript
✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · yes
✔ Where does your code run? · browser
The config that you've selected requires the following dependencies:

eslint, @eslint/js, globals, typescript-eslint
✔ Would you like to install them now? · yes
  1. eslint.config.mjs 文件

如果有ts,需要添加 parse 字段,来指定eslint代码解析器,默认eslint使用的是js解析

import js from '@eslint/js'
import tseslint, { tsParser } from 'typescript-eslint'
import globals from 'globals'

export default [
	{
		files: ['**/*.{js,ts,tsx,jsx}'],
		languageOptions: {
			ecmaVersion: 2021,
			sourceType: 'module',
			globals: {
				...globals.browser,
				...globals.node,
				...globals.jest
			}
		},
		// 指定eslint代码解析器,默认eslint使用的是js解析
		parser: tsParser,
		plugins: {
			'@typescript-eslint': tseslint.plugin,
		},
		rules: {
			// 添加js推荐规则
			...js.configs.recommended.rules,
			// 添加typescript-eslint推荐规则
			...tseslint.configs.recommended[0].rules,
			'prettier/prettier': 'error',
			'no-case-declarations': 'off',
			'no-constant-condition': 'off',
			'@typescript-eslint/ban-ts-comment': 'off',
			'@typescript-eslint/no-unused-vars': 'off',
			'@typescript-eslint/no-var-requires': 'off',
			'no-unused-vars': 'off'
		}
	}
]

格式规范 prettier

  1. 安装
pnpm i prettier -D -w
  1. 新增 .prettierrc.json 文件
{
	"printWidth": 80,
	"tabWidth": 2,
	"useTabs": true,
	"singleQuote": true,
	"semi": false,
	"trailingComma": "none",
	"bracketSpacing": true
}

将 eslint 和 prettier 集成

  1. 安装
pnpm i eslint-config-prettier eslint-plugin-prettier -w -D
  1. 新增 lint 脚本
"scripts": {
    "lint": "eslint --ext .js,.ts,.jsx,.tsx --fix --quiet ./packages"
}
  • ext:处理文件类型
  • fix:修复错误
  • quiet:不输出反馈
  1. 修改 .eslint.config.mjs 文件
import js from '@eslint/js'
import tseslint from 'typescript-eslint'
import globals from 'globals'
+ import pluginPrettier from 'eslint-plugin-prettier'

export default [
	{
		files: ['**/*.{js,ts,tsx,jsx}'],
		languageOptions: {
			ecmaVersion: 2021,
			sourceType: 'module',
			globals: {
				...globals.browser,
				...globals.node,
				...globals.jest
			}
		},
		plugins: {
			'@typescript-eslint': tseslint.plugin,
+ 			prettier: pluginPrettier
		},
		rules: {
			// 添加js推荐规则
			...js.configs.recommended.rules,
			// 添加typescript-eslint推荐规则
			...tseslint.configs.recommended[0].rules,
			'prettier/prettier': 'error',
			'no-case-declarations': 'off',
			'no-constant-condition': 'off',
			'@typescript-eslint/ban-ts-comment': 'off',
			'@typescript-eslint/no-unused-vars': 'off',
			'@typescript-eslint/no-var-requires': 'off',
			'no-unused-vars': 'off'
		}
	}
]

commit 提交规范

  1. 安装 husky,用于拦截 git commit 命令,并执行相应的脚本
pnpm i husky -D -w
  1. 初始化 husky

在初始化前,务必在本地 commit 提交一次

pnpm husky init
  1. lint 命令添加到 commithusky 执行的脚本
huky add .husky/pre-commit "pnpm lint"

也可以手动在 .husky/pre-commit 文件中添加 pnpm lint 内容

  1. 使用 lint-staged

pnpm lint 会对代码进行全量检查,当项目复杂后执行速度可能会比较慢,这时候可以考虑使用 lint-staged,实现只对暂存区代码进行检查

  1. 通过 commitlintgit 提交信息进行检查,首先安装必要的库:
pnpm i commitlint @commitlint/config-conventional -D -w
  1. 新增 commitlint.config.mjs 文件
export default { extends: ['@commitlint/config-conventional'] }

也可以执行:

echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.mjs
  1. commitlint 集成到 husky
# 在 .husky/commit-msg 文件夹中写入 npx --no -- commitlint --edit $1
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg

conventional 规范集意义:

<type>: <subject>提交类型: 摘要信息

常用 type 值:

  • feat:新功能
  • fix:修复 bug
  • docs:文档
  • style:格式化
  • refactor:重构
  • perf:性能优化
  • test:测试
  • build:构建
  • ci:持续集成
  • chore:其他

当你通过 git commit -m 'xxx' 时就会报错,commit 信息必须为 aa: bb 格式才行

  1. git cz 可视化提交

  2. 安装 cz-vinyl(1的版本)

cz-vinyl 是一个 commitizen 适配器,用于在终端中提供一个交互式命令行界面(CLI)。

pnpm i cz-vinyl@1 -D -w
  1. 全局安装 commitizen
npm install -g commitizen
  1. 修改 package.json 文件

添加内容的目的是用于告诉全局命令行工具 commitizen(CLI):当你运行 git cz 时,应该使用哪个适配器来生成提交信息。

"scripts": {},
"config": {
  // commitizen:键名,给全局安装的 commitizen CLI 使用的配置
  "commitizen": {
    "path": "./node_modules/cz-vinyl"
  }
}

流程为:

当你在终端执行 git cz 时,git 会调用 commitizen CLIcommitizen 会加载你指定的适配器 cz-vinyl,然后弹出交互式界面,引导你填写符合 Conventional Commits 规范的提交信息。

填写完成后这个信息后, husky 会先触发 pre-commit 文件的钩子,也就是触发 lint-staged 对暂存区文件进行代码格式校验,然后再通过 commit-msg 钩子校验提交信息规范。

git cz
cz-cli@4.3.0, cz-vinyl@1.6.2

? Select the type of changes you're commiting:
 
❯ 🔥 feat: A new feature 
  🐞 fix: A bug fix 
  ⚡ perf: A code change that improves performance 
  💡 refactor: A code change that neither fixes a bug or adds a feature 
  🔖 release: Create a release commit 
  🎨 style: Markup, white-space, formatting, missing semi-colons... 
  ✅ test: Adding missing tests 

问:为什么是 cz

答:git 检测到别名 cz,因为 git 支持命令别名,cz 是 commitizen 提供的一个别名,当运行 git cz 时,git 会识别为 git commit

  1. 可视化命令行汉化,新增 .czvinylrc 文件
{
    "headerFormat": "{type}({scope}): {subject}",
    "commitTypes": [
        {
            "description": "一个新的功能",
            "value": "feat"
        },
        {
            "description": "一个BUG修复",
            "value": "fix"
        },
        {
            "description": "辅助工具更改或者无法分类的提交",
            "value": "chore"
        },
        {
            "description": "提高性能的代码更改",
            "value": "perf"
        },
        {
            "description": "不修复错误也不增加功能的重构代码",
            "value": "refactor"
        },
        {
            "description": "更新代码格式",
            "value": "style"
        },
        {
            "description": "添加测试用例",
            "value": "test"
        },
        {
            "description": "更新文档",
            "value": "docs"
        },
        {
            "description": "更新CI发版代码",
            "value": "ci"
        },
        {
            "description": "更新构建依赖等模块",
            "value": "build"
        }
    ],
    "skipScope": false,
    "skipTicketId": true,
    "subjectMaxLength": 70,
    "subjectMinLength": 3,
    "typeQuestion": "请选择一个提交类型:",
    "scopeQuestion": "请输入一个改动范围:",
    "subjectQuestion": "请输入一个提交信息:",
    "bodyQuestion": "请输入一个提交详细内容(可跳过):"
}

ts 配置

新增 tsconfig.json 文件

{
	"compileOnSave": true,
	"compilerOptions": {
		"target": "ESNext",
		"useDefineForClassFields": true,
		"module": "ESNext",
		"lib": ["ESNext", "DOM"],
		"moduleResolution": "Node",
		"strict": true,
		"sourceMap": true,
		"resolveJsonModule": true,
		"isolatedModules": true,
		"esModuleInterop": true,
		"noEmit": true,
		"noUnusedLocals": false,
		"noUnusedParameters": false,
		"noImplicitReturns": false,
		"skipLibCheck": true,
		// ts基础入口
		"baseUrl": "./packages"
	}
}

网站公告

今日签到

点亮在社区的每一天
去签到