前端工程化之代码规范

🤔为什么需要代码规范

  • 提升代码可读性、可维护性
  • 促进团队协作效率,减少沟通成本
  • 避免常见错误(如全局变量污染、样式冲突)

ESLint

用于识别和报告 ECMAScript/JavaScript 代码中发现的模式的工具,目的是使代码更加一致并避免错误。

安装

npm init @eslint/config@latest初始化ESLint时会生成基础的配置。

配置

配置文件为eslint.config.jseslint.config.mjs,版本9.0.0之前配置为.eslintrc.8

javascript 复制代码
// eslint.config.js
import js from "@eslint/js";

export default [
    js.configs.recommended, // ESLint推荐的规则
    {
        // https://eslint.org/docs/latest/use/configure/configuration-files
        files: ["**/*.{js,mjs,cjs,ts}"] // 指定文件,忽略优先
    },
    {
        // https://eslint.org/docs/latest/use/configure/ignore
        ignores: [".config/*"] // 忽略文件(老版本创建.eslintignore文件)
    },
    {
        // https://eslint.org/docs/latest/use/configure/language-options
        languageOptions: {
            ecmaVersion: 5, // ECMAScript 版本
            sourceType: "module" // JavaScript 文件的模式
        },
    },
    {
        // https://eslint.org/docs/latest/rules/
        rules: {
            'no-unused-vars': 'off', // 禁止未使用变量
            'eqeqeq': 'warn', // 要求使用===和!==
            'no-var': 'error' // 禁止使用var
        }
    }
];
  • "off"0 - 关闭规则。
  • "warn"1 - 将规则作为警告打开(不影响退出代码)。
  • "error"2 - 将规则作为错误打开(触发时退出代码为 1)。

命令行界面参考

sh 复制代码
npx eslint [filename] #单个文件
npx eslint . #所有文件
npx eslint --fix . #尝试尽可能多的问题。

--fix并不能修复所有问题,只能修复部分问题,具体在规则中可见。

更多命令

IDE配置

Webstorm: 右键ESLint配置文件,选择apply eslint rules

Prettier

格式化程序,让代码保持一致的风格。

安装

npm install --save-dev --save-exact prettier

配置

需自行创建配置文件.prettierrc

json 复制代码
{
    "printWidth": 100,              // 每行代码字符数,超出换行
    "semi": false,                  // 每个语句末尾添加分号 
    "singleQuote": false,           // 使用单引号代替双引号
    "tabWidth": 2,                  // 每行缩进的空格数
    "bracketSpacing": true,         // 对象中文本和括号之间是否要空格
    "arrowParens": "always"         // 箭头函数只有一个参数时是否加()
    ... // https://prettier.io/docs/options
}

插件

prettier-plugin-tailwindcss

tailwindcss类名进行排序。

json 复制代码
{
    ...
    "plugins": ["prettier-plugin-tailwindcss"],
    "tailwindAttributes": ["myClassList"],
    "tailwindFunctions": ["clsx"]  //对clsx函数实参的字符串排序,变量不行
}

命令行界面参考

sh 复制代码
prettier [filename] --write #识别单个文件
prettier . --write #识别所有文件
prettier . --check #只检查文件是否已格式化,不自动格式化

更多命令

Git Hooks

本地

  • pre-commit:在创建提交之前运行,常用于运行测试或代码检查工具(如 ESLint)。
  • commit-msg:在提交消息被创建后运行,常用于验证提交消息的格式或内容。
  • pre-push:在执行推送操作之前运行,通常用于确保推送的代码不破坏远程仓库的代码。
  • pre-rebase:在执行 rebase 操作之前运行,可以用于基于某些条件来阻止某些操作。
  • post-commit:在提交完成后运行,常用于发送通知或记录日志。

远程

  • `pre-receive:在远程仓库接收推送之前执行,允许你拒绝或修改推送的更改。
  • update:在每个分支更新时执行,用于针对特定分支应用检查或策略。
  • post-receive:在远程仓库接收到推送之后执行,常用于触发部署或发送通知。

存放位置

存放在 .git/hooks/ 目录下。你会看到一些带有 .sample 后缀的示例脚本文件,可以根据需要进行自定义。要启用某个 hook,只需要删除 .sample 后缀并编写你的脚本。

core.hooksPath记录hooks存放的路径。默认为空,指向.git/hooks/

sh 复制代码
git config core.hooksPath                  #查看
git config --unset core.hooksPath          #重置
git config core.hooksPath [path]           #设置

Husky

Git 钩子管理工具,用于在 Git 操作(如提交、推送)前后自动执行脚本, 如提交代码前运行 ESLint 和 Prettier 保证代码风格一致性。

安装

sh 复制代码
npm install --save-dev husky
npx husky init

init操作后会创建.husky目录。目录下_为Git Hooks存放位置,并将core.hooksPath指向了该目录。pre-commit文件会在Git提交前执行。还会在package.json->scripts->prepare中添加husky命令,prepare会在npm installnpm publish时执行,相当于init操作。

lint-staged

只对暂存区的文件进行操作。

安装

npm install --save-dev lint-staged

配置

package.json .lintstagedrc.* lint-staged.config.js .lintstagedrc.js

package.json 复制代码
{
    ...
    "lint-staged": {
        "*": ["prettier --write"],
        "*.{js,jsx,ts,tsx,vue}": "eslint --fix"
    }
}

.husky/per-commit中添加npx lint-staged

总结

使用 Huskylint-staged 来对暂存区文件在提交前运行 ESLintPrettier 来优化代码质量。

相关推荐
狂炫冰美式4 分钟前
不谈技术,搞点文化 🧀 —— 从复活一句明代残诗破局产品迭代
前端·人工智能·后端
xw51 小时前
npm几个实用命令
前端·npm
!win !1 小时前
npm几个实用命令
前端·npm
代码狂想家1 小时前
使用openEuler从零构建用户管理系统Web应用平台
前端
dorisrv2 小时前
优雅的React表单状态管理
前端
蓝瑟3 小时前
告别重复造轮子!业务组件多场景复用实战指南
前端·javascript·设计模式
dorisrv3 小时前
高性能的懒加载与无限滚动实现
前端
韭菜炒大葱3 小时前
别等了!用 Vue 3 让 AI 边想边说,字字蹦到你脸上
前端·vue.js·aigc
StarkCoder3 小时前
求求你,别在 Swift 协程开头写 guard let self = self 了!
前端
清妍_3 小时前
一文详解 Taro / 小程序 IntersectionObserver 参数
前端