ESLint + Prettier + husky + lint-staged 规范统一前端代码风格

5,455 阅读3分钟

写在前面:

  • ESLint: Find and fix problems in your JavaScript code.
  • Prettier: Prettier is an opinionated code formatter.
  • Husky: Husky can prevent bad git commit, git push and more.
  • Lint-staged: Run linters against staged git files and don't let 💩 slip into your code base!
  • EditorConfig: EditorConfig helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs.
  • Stylelint: A mighty, modern linter that helps you avoid errors and enforce - conventions in your styles.
  • 开发工具:VS Code、插件: Prettier,ESLint
  • 开发框架:React V16+、React CLI
  • 版本控制:Git
  • 参考资料:

搭建项目:

npx create-react-app [your-project-name]
cd [your-project-name]
# npm run eject

初始化 ESLint 配置文件:

./node_modules/.bin/eslint --init

根据问题选择自己喜欢的配置(选错也没事,后面可以在配置文件里修改)完成以后会在项目根目录生成 .eslintrc.js 文件。

Eslint init

.eslintrc.js:

module.exports = {
  env: {
    browser: true,
    es6: true,
    node: true,
  },
  extends: 'eslint:recommended',
  globals: {
    Atomics: 'readonly',
    SharedArrayBuffer: 'readonly',
    _: true,
  },
  parser: 'babel-eslint', // 解决 实验性的 public class fields 语法 报错问题
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2018,
    sourceType: 'module',
  },
  plugins: ['react', 'react-hooks'],
  rules: {
    'react-hooks/rules-of-hooks': 'error', // 检查 Hook 的规则
    'react-hooks/exhaustive-deps': 'warn', // 检查 effect 的依赖
    indent: [
      'error',
      2,
      {
        SwitchCase: 1,
      },
    ],
    // 'linebreak-style': ['error', 'unix'], // 换行符 Mac:'unix' -> LF,win:'windows' -> CRLF
    quotes: ['error', 'single'],
    semi: ['error', 'always'],
    'multiline-ternary': ['error', 'always-multiline'], // 三目运算符换行
    'react/jsx-uses-react': 'error', // Prevent React to be incorrectly marked as unused
    'react/jsx-uses-vars': 'error', // Prevent variables used in JSX to be incorrectly marked as unused
    'no-console': 'off',
  },
};

初始化 Prettier 配置:

在根目录下新建 .prettierrc.js 文件:

module.exports = {
  trailingComma: 'all',
  printWidth: 80,
  tabWidth: 2,
  semi: true,
  singleQuote: true,
  jsxBracketSameLine: true,
  jsxSingleQuote: true,
  arrowParens: 'always',
};

安装 Prettier、husky、lint-staged:

npm install --save-dev --save-exact prettier
npm install --save-dev husky
npm install --save-dev lint-staged

注意:一定要使用 --save-dev 安装在 devDependencies 下。

初始化 lint-staged 配置:

npx mrm lint-staged

完成后会在 package.json 中生成 husky 和 lint-staged 配置(以下为手动修改后的配置):

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,jsx,css,less,json,md}": [
      "prettier --write",
      "git add"
    ],
    "**/*.less": "stylelint --syntax less",
    "**/*.{js,jsx}": "npm run lint-staged:js"
  },

配置 stylelint:

npm install stylelint --save-dev

在根目录下新建 .stylelintrc.js 文件:

module.exports = {
  extends: 'stylelint-config-standard',
  rules: {
    'block-no-empty': true,
    'comment-empty-line-before': [
      'always',
      {
        ignore: ['stylelint-commands', 'after-comment'],
      },
    ],
    indentation: [2],
    'max-empty-lines': 2,
  },
};

可能会遇到以下报错:

Could not find "stylelint-config-standard". Do you need a `configBasedir`?

解决方案:

查看:stylelint-config-standard

npm install stylelint-config-standard --save-dev

配置 package.json 中的脚本命令:

"scripts": {
    "lint": "npm run lint:js && npm run lint:style && npm run lint:prettier",
    "lint-staged": "lint-staged",
    "lint-staged:js": "eslint --ext .js,.jsx,.ts,.tsx ",
    "lint:fix": "eslint --fix --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src && npm run lint:style",
    "lint:js": "eslint --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src",
    "lint:prettier": "check-prettier lint",
    "lint:style": "stylelint --fix \"src/**/*.less\" --syntax less",
    "prettier": "prettier -c --write \"**/*\""
  },

VS Code 安装 Prettier、ESLint 插件(不会的自行 Google)

Prettier Plugin

Eslint Plugin

配置 VS Code 编辑器:

VSCode Config

这里只示例配合 prettier 插件使用的配置,当保存文件的时候将自动格式化代码:

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true
}

创建可移植的自定义编辑器设置:

在根目录下新建 .editorconfig 文件,配置如下:

# http://editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[Makefile]
indent_style = tab

其他配置:

如果不需要 ‘行结束符’ 配置,则 把 .editorconfig 中的 end_of_line.eslintrc.js 文件中 rules 下的 linebreak-style 注释掉,或者干脆不配置editorconfig文件,使用默认配置。

在项目根目录新建 .gitattributes 文件,配置如下:

* text=auto

'linebreak-style': ['error', 'unix'], // 换行符。 Mac 使用 'unix' 对应 LF,Win 使用 'windows' 对应 CRLF


如果需要 ‘行结束符’ 配置,例如使用 LF 。则 .editorconfig 中配置 end_of_line = lf.eslintrc.jsrules 配置 linebreak-style: ['error', 'unix']

另外再给 VS Code 配置 "files.eol": "\n",最好再给 .gitattributes 添加配置 *.js text eol=lf*.jsx text eol=lf 等等,全部提交之后,把本地项目文件全删除,重新 clone。

.gitattributes 配置参考网上的。一般不用这个 行结束符 配置。

参考:line endings


写在最后:

以上配置均可在 写在最前 的链接中找到,可以根据自己的风格进行配置。