Next.js14+prettier3+eslint8+husky9配置

307 阅读3分钟
  • ESlint关注代码的质量+潜在问题(TS、JS检查潜在错误、代码风格一致性、最佳实践写法);Prettier关注代码格式+样式(格式化、缩进、空格、换行);通常两者同时使用。
  • Husky是一个Git hooks工具,在Git操作(commit、push等)前运行特定脚本,确保代码质量+一致性,避免不符合标准的代码commit到版本控制中。

prettier3配置

NextJS set up with TypeScript, ESLint and Prettier

  • package.json文件配置:
"scripts": {
    "format": "prettier --check .",
    "format:fix": "prettier --write --list-different .",
}
  • 创建.prettierrc.js文件,配置内容如下:
module.exports = {
  printWidth: 120, // max 120 chars in line, code is easy to read
  useTabs: false, // use spaces instead of tabs
  tabWidth: 2, // "visual width" of of the "tab"
  trailingComma: 'es5', // add trailing commas in objects, arrays, etc.
  semi: false, // add ; when needed
  singleQuote: true, // '' for stings instead of ""
  bracketSpacing: true, // import { some } ... instead of import {some} ...
  arrowParens: 'always', // braces even for single param in arrow functions (a) => { }
  jsxSingleQuote: false, // "" for react props, like in html
  bracketSameLine: false, // pretty JSX
  endOfLine: 'lf', // 'lf' for linux, 'crlf' for windows, we need to use 'lf' for git
}
  • README.md文件添加命令:
# 检查格式
npm run format
# 修复格式问题
npm run format:fix

eslint8配置

{
  "extends": ["next/core-web-vitals", "prettier"]
}

husky配置

  • 防止错误提交:设置条件,阻止不符合要求的提交。若未通过lint检查,拒绝提交。
  • 简化开发流程:自动化检查,减少手动执行,提升开发效率。
  • 参考配置:(typicode.github.io/husky/how-t…)
  • .husky/pre-commit文件下,配置(该配置可不写,若配置lint-staged包含以下2个命令):
# 预提交检查,确保代码质量
npm run lint
# 格式化代码,保持代码风格一致性
npm run format:fix

Commitlint19配置

  • 检查Git提交信息是否符合特定的约定or格式。确保commit一致性+可读性。
  1. 标准化commit信息:使用特定前缀featfix等,遵循相同规范。
  2. 集成与自动化:与Husky搭配使用,在提交前自动检查commit信息是否符合要求。
  3. commitlint.config.js文件参考配置:(github.com/conventiona…)
export default {
    extends: ['@commitlint/config-conventional'],
}
  1. 用正确的commit格式,报错处理:(stackoverflow.com/questions/7…)
  2. @commitlint/config-conventional 是基于 conventional commits 规范的配置文件。
  3. @commitlint/cli 是 commitlint 工具的核心。
  • package.json文件添加下面代码:
"commitlint": {
    "extends": [
      "@commitlint/config-conventional"
    ]
}

lint-staged配置

  • 以上配置问题:若IDE没有配置自动修复格式,commit时会先fix,需要再执行一次commit,由此会产生2次commit记录,不友好。
  • 在Git提交时,仅对已暂存的文件运行linting和格式化。
  • Husky搭配使用,在Git提交钩子中自动触发lint-staged检查。
npm install lint-staged -D
  • 在文件package.json配置,管理格式化内容:
"lint-staged": {
    "*.{js,jsx,vue,ts,tsx}": [
      "prettier --write",
      "npm run lint:fix"
    ]
},
  • .husky/pre-commit文件配置:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# 会执行 Prettier格式化与ESLint修复
npx lint-staged
  • .husky/commit-msg文件配置:
npx --no -- commitlint --edit ${1}

VSCode插件code spell checker

  • 自动检查单词的拼写是否正确,支持驼峰命名

参考资料