首页 > 解决方案 > 如何将 git prehook 添加到 tslint?

问题描述

如果代码有任何 linting 问题无法提交,我正在尝试添加 prehook。实现它的正确方法是什么。

tslint.sh

#!/bin/sh
sh ./npm-install.sh
if [ $? -ne 0 ]; then
  echo "npm-install error, exiting.."
  exit 1
fi
echo "Running ts lint"
npm run lint
if [ $? -ne 0 ]; then
  echo "Unit tests error, exiting.."
  exit 1
fi

标签: node.jsgittslint

解决方案


我有一个成功的经验来实现这一点:

  1. husky=> 指定 git 钩子
  2. lint-staged=> 对 git 中的暂存文件运行命令(因此无需对所有文件运行 tslint)

参考:

  1. https://github.com/okonet/lint-staged
  2. https://www.npmjs.com/package/husky

在,package.json指定lint-staged和字段:pre-commithusky

"dependencies": ...,
"devDependencies": ...,
"scripts" ...,
"husky": {
    "hooks": {
        "pre-commit": "lint-staged"
    }
},
"lint-staged": {
    "*.ts": [ // target to all typescript files in staged stage in git
      "npm run lint", // your lint command
      "git add"   
    ]
}

推荐阅读