Tom*_*Tom 12 pre-commit-hook typescript tslint husky lint-staged
采用以下Typescript箭头功能:
/**
* Returns a probably unique component name.
*
* @param baseName a suggested name to make unique.
* @returns a probably unique name.
*/
export const getUniqueComponentName = (
baseName
): string => {
return baseName + Math.round(Math.random() * 10000000)
}
Run Code Online (Sandbox Code Playgroud)
当Typescript配置tsconfig.json为这样时:
"noImplicitAny": true,
Run Code Online (Sandbox Code Playgroud)
这正确导致编译错误:
[ts]参数'baseName'隐式具有'any'类型.
Visual Studio Code也非常智能,可以在开发过程中告知您这个问题.
我的目标是创建一个precommit git hook,以防止此类错误在版本控制中结束.我试着这样做tslint,husky并lint-staged使用这个npm script:
"lint": "tslint --project tsconfig.json --config tslint.json"
Run Code Online (Sandbox Code Playgroud)
但是,这不会导致tslint显示编译错误.它被默默地忽略了.
然后我尝试在tslint.json中添加一条规则:
"typedef": [
true,
"arrow-parameter"
]
Run Code Online (Sandbox Code Playgroud)
虽然这确实让tslint抱怨,但它也开始抱怨匿名箭头函数,tsc编译器不抱怨.在这些箭头函数中,不需要添加类型,因为先前已在父作用域中设置了类型(它们是推断的).
所以基本上,我希望tslint在这种情况下的行为与tsc相同.任何时候有一个错误导致编译失败(例如上面的箭头函数),我想阻止提交,但没有实际编译为Javascript.这可能吗?
我认为最好的办法是运行tsc --noEmit -p .并过滤输出中修改过的文件中的错误.例如,我将以下脚本保存到tsc-some-files:
#!/bin/bash
declare -A include_files
for f in "$@"; do
include_files["${f#$PWD/}"]=1
done
node_modules/.bin/tsc --noEmit -p . | (
status=0
show_continuation=false
while IFS='' read -r line; do
case "$line" in
(' '*)
if $show_continuation; then
echo "$line" >&2
fi
;;
(*)
file="${line%%(*}"
if [ -n "${include_files["$file"]}" ]; then
show_continuation=true
echo "$line" >&2
status=1
else
show_continuation=false
fi
;;
esac
done
exit $status
)
Run Code Online (Sandbox Code Playgroud)
并设置./tsc-some-files为我的lint-staged命令,它似乎工作.(如果需要,用bash以外的编程语言写这个,留给读者练习.)
请记住,编辑一个文件可能会在另一个文件中引入错误(例如,如果您更改了另一个文件正在使用的内容的类型),那么我建议您尽快清除TypeScript错误必要的黑客攻击(只要你标记它们以便以后可以搜索它们)然后设置你的钩子就可以在整个项目中没有错误.事实上,noImplicitAny特别是几年前我将一个JavaScript项目迁移到TypeScript时,我编写了一个脚本,在any任何地方插入一个隐式any错误,然后我any在闲暇时修复了显式s.如果你有兴趣,我可以分享剧本.
| 归档时间: |
|
| 查看次数: |
2971 次 |
| 最近记录: |