为项目追加lint-staged并解决gitlab-ci的问题

237 阅读1分钟

背景

来了新项目后发现代码很乱,各种变量声明了不用,各种console...

项目已有husky,打算通过lint-staged配合husky校验提交的diff代码

安装配置 lint-staged

npm i lint-staged --save-dev

在根目录添加.lintstagedrc文件

{
  "src/**/*.{ts,vue}": [
    "prettier --write",
    "eslint --fix"
  ]
}

添加git hooks,即在commit时会执行的命令

npx husky add .husky/pre-commit "npx lint-staged"

添加后会在./husky/pre_commit文件中看到多了一条npx lint-staged

. "$(dirname -- "$0")/_/husky.sh"

npx lint-staged # 执行命令后多出的一行

安装配置 lint-staged

添加想要拦截commit的eslint规则,举几个常见且不太能忍的:

rulse: {
      'no-console': ['error', { allow: ['error'] }],
      'no-magic-numbers': [
        'warn',
        {
          ignore: [0, 1],
        },
      ],
      '@typescript-eslint/no-unused-vars': 'error',
    }

解决gitlab-CI的问题

本地提commit的时候lint-staged只会校验当前diff的代码,以前的烂代码不会校验。 不过gitlab在提mr的时候会跑一个pipeline,其中会跑全局的eslint校验,上面改了eslint规则后,会导致pipeline失败。

最开始的时候想通过修改.gitlab-ci.yml文件,让它只跑当前mr中包含的commit,不过.gitlab-ci.yml搞不太明白。最后是通过动态配置eslint规则的方式解决的,通过process.env.CI === 'true'判断是CI环境,配置一套eslint规则。

.eslintrc文件中做如下改动:

...

rulse: getDynamicRules()

...
function getDynamicRules() {
  if (process.env.CI === 'true') {
    return {
      'vue/multi-word-component-names': [
        'warn',
        {
          ignores: ['index'],
        },
      ],
    }
  } else {
    return {
      'vue/multi-word-component-names': [
        'warn',
        {
          ignores: ['index'],
        },
      ],
      'no-console': ['error', { allow: ['error'] }],
      'no-magic-numbers': [
        'warn',
        {
          ignore: [0, 1],
        },
      ],
      '@typescript-eslint/no-unused-vars': 'error',
    }
  }
}