React项目快速搭配eslint,prettier,commitlint,lint-staged

1,545 阅读5分钟

为了实现代码规范,我们在使用中会使用诸多插件,比如eslintprettiercommitlintstylelint等等,在新项目中这样一套组合拳下来,也是稍显繁琐,另外还要定制配置文件,某种程度上来说是体力活。

本文的目的是介绍如何简化配置,统一规范。

1. magic-lint

magic-lint是一款代码规范工具,集检查、美化于一体,能够检查commit信息,通过hook在代码提交时规范代码,里面包含这些:

  • eslint
  • stylelint
  • prettier
  • lint-staged
  • husky
  • commitlint

使用magic-lint之后就不需要单独安装上述插件,可以无门槛使用。

1.1 安装

npm install magic-lint --save-dev

1.2 参数

Usage: magic-lint [options] file.js [file.js] [dir]

# 提交commit触发校验
magic-lint --commit

# 对指定路径 lint
magic-lint --prettier --eslint --stylelint src/

# 只对提交的代码进行 lint
magic-lint --staged --prettier --eslint --stylelint

# 对于某些场景需要指定 lint 工具的子参数
magic-lint --eslint.debug  -s.formatter=json -p.no-semi

Options:
--commit, -C              only check commit msg                               [boolean] [default: false]
--staged, -S              only lint git staged files                          [boolean] [default: false]
--prettier, -p            format code with prettier                           [boolean] [default: false]
--eslint, -e              enable lint javascript                              [boolean] [default: false]
--stylelint, --style, -s  enable lint style                                   [boolean] [default: false]
--fix, -f                 fix all eslint and stylelint auto-fixable problems  [boolean] [default: false]
--quiet, -q               report errors only                                  [boolean] [default: false]
--cwd                     current working directory                           [default: process.cwd()

2. 配置

2.1 基础配置

package.json中添加如:

+ "husky": {
+   "hooks": {
+     "pre-commit": "magic-lint --staged --eslint --stylelint --prettier --fix"",
+     "commit-msg": "magic-lint --commit"
+   }
+ }

2.2 eslint

eslint是一款代码检查工具,使用的时候还需添加具体的配置文件。在React项目中我们一般会使用eslint-config-airbnb

通过执行如下命令可以看到依赖包的版本:

npm info "eslint-config-airbnb@latest" peerDependencies

我们得到如下内容:

{
   eslint: '^5.16.0 || ^6.1.0',
  'eslint-plugin-import': '^2.18.2',
  'eslint-plugin-jsx-a11y': '^6.2.3',
  'eslint-plugin-react': '^7.14.3',
  'eslint-plugin-react-hooks': '^1.7.0'
}

如果使用的npm版本大于4,可以使用下面的命令快速安装依赖,无需手动敲打:

npx install-peerdeps --dev eslint-config-airbnb

安装完成之后在项目根目录创建.eslintrc.js,同样可以使用下面的命令,或者手动创建:

./node_modules/.bin/eslint --init
module.exports = {
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": "airbnb",
    "globals": {
        "Atomics": "readonly",
        "SharedArrayBuffer": "readonly"
    },
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
    }
};

eslint-config-airbnb本质是eslint配置的定制合集,其实我们也可以根据自身情况维护一套配置,这样在协作中的项目可以统一配置,避免配置的来回复制。

2.3 prettier

prettiereslint需要搭配使用,使用prettier能让我们在保存或者提交代码时格式化代码,避免不同编辑器、开发环境导致的格式问题。

prettier的配置不多,具体的配置介绍可以看下面的介绍,大家结合eslint的规则配置即可。

这里我们使用.prettierrc.js配置方式。

module.exports = {
  // 一行最多 150 字符
  printWidth: 150,
  // 使用 4 个空格缩进
  tabWidth: 4,
  // 不使用缩进符,而使用空格
  useTabs: false,
  // 行尾需要有分号
  semi: true,
  // 使用单引号
  singleQuote: true,
  // 对象的 key 仅在必要时用引号
  quoteProps: 'as-needed',
  // jsx 不使用单引号,而使用双引号
  jsxSingleQuote: false,
  // 末尾是否需要逗号
  trailingComma: 'es5',
  // 大括号内的首尾需要空格
  bracketSpacing: true,
  // jsx 标签的反尖括号需要换行
  jsxBracketSameLine: false,
  // 箭头函数,只有一个参数的时候,也需要括号
  arrowParens: 'always',
  // 每个文件格式化的范围是文件的全部内容
  rangeStart: 0,
  rangeEnd: Infinity,
  // 不需要写文件开头的 @prettier
  requirePragma: false,
  // 不需要自动在文件开头插入 @prettier
  insertPragma: false,
  // 使用默认的折行标准
  proseWrap: 'preserve',
  // 根据显示样式决定 html 要不要折行
  htmlWhitespaceSensitivity: 'css',
  // 换行符使用 lf
  endOfLine: 'lf',
};

这里同样也有排除文件.prettierignore,语法规则和.gitignore一样。

2.4 stylelint

stylelint是一款css代码规范工具,magic-lint里面已经预置了一些配置和插件:

  • stylelint-config-css-modules
  • stylelint-config-prettier
  • stylelint-config-rational-order
  • stylelint-config-standard
  • stylelint-declaration-block-no-ignored-properties
  • stylelint-order

配置文件可以命名.stylelintrc.json,填充如下内容:

{
  "extends": ["stylelint-config-standard", "stylelint-config-css-modules", "stylelint-config-rational-order", "stylelint-config-prettier"],
  "plugins": ["stylelint-order", "stylelint-declaration-block-no-ignored-properties"],
  "rules": {
    "no-descending-specificity": null,
    "plugin/declaration-block-no-ignored-properties": true
  }
}

忽略文件的名称是.stylelintignore,遵循.gitignore语法。

2.5 commitlint

commitlint是一款校验commit提交信息的工具,它可以让我们的提交信息更规范、更有可读性,甚至可以基于提交自动生成changelog

commit的格式要求如下,这段内容同样也可以直接用到git提交模板:

Type(<scope>): <subject>

<body>

<footer>

# Type 字段包含:
#  feat:新功能(feature)
#  fix:修补bug
#  docs:文档(documentation)
#  style: 格式(不影响代码运行的变动)
#  refactor:重构(即不是新增功能,也不是修改bug的代码变动)
#  test:增加测试
#  chore:构建过程或辅助工具的变动
# scope用于说明 commit 影响的范围,比如数据层、控制层、视图层等等。
# subject是 commit 目的的简短描述,不超过50个字符
# Body 部分是对本次 commit 的详细描述,可以分成多行
# Footer用来关闭 Issue或以BREAKING CHANGE开头,后面是对变动的描述、
#  以及变动理由和迁移方法

例子:

git commit -m 'feat: 增加用户搜搜功能'
git commit -m 'fix: 修复用户检测无效的问题'

magic-lint已经内置@commitlint/config-conventional配置方案,它里面包含了以下几个type:

'build',
'ci',
'chore',
'docs',
'feat',
'fix',
'perf',
'refactor',
'revert',
'style',
'test'

3. 写在最后

在前端开发中,需要配置的内容太多太多了,大把的时间花在配置上就真的变成了"前端配置师"。

可能这也是我们都愿意造轮子的原因了,不过最终在工作中能起到作用的轮子就是好轮子。同样如果只是使用别人的轮子,自己又如何能成长呢!

本文同步发表于作者博客: React项目快速搭配eslint,prettier,commitlint,lint-staged