前端代码风格自动化系列(三)之Lint-staged

33次阅读

共计 1156 个字符,预计需要花费 3 分钟才能阅读完成。

在我们介绍了 Husky、Commitlint 之后,来看一个前端文件过滤的工具 Lint-staged,代码的格式化肯定会涉及到文件系统,一般工具会首先读取文件,格式化操作之后,重新写入。对于较大型的项目,文件众多,首先遇到的就是性能问题,虽然如 Eslint 之类的也有文件过滤配置,但毕竟还是对于匹配文件的全量遍历,如全量的.js 文件,基本达不到性能要求,有时还会误格式化其他同学的代码,因此我们引入 Lint-staged,一个仅仅过滤出 Git 代码暂存区文件 (被 committed 的文件) 的工具。
安装
npm install –save-dev lint-staged husky
配置
首先明确一下,Lint-staged 仅仅是文件过滤器,不会帮你格式化任何东西,所以没有代码规则配置文件,需要自己配置一下,如:.eslintrc、.stylelintrc 等,然后在 package.json 中引入。
{
“husky”: {
“hooks”: {
“pre-commit”: “lint-staged”
}
},
“lint-staged”: {
“*.js”: [“eslint –fix”, “git add”]
}
}
当文件变化,我们 git commit 它们,pre-commit 钩子会启动,执行 lint-staged 命令,我们对于 lint-staged 如上文配置,对本次被 commited 中的所有.js 文件,执行 eslint –fix 命令和 git add, 命令,前者的的目的是格式化,后者是对格式化之后的代码重新提交。
除了在 package.json 中配置,也可以在.lintstagedrc、lint-staged.config.js 文件中,lint-staged 的常用选项除了 liners 之外,还有 ignore、concurrent 等,具体参考文档:
{
“lint-staged”: {
“linters”: {
“*.{js,scss}”: [“some command”, “git add”]
},
“ignore”: [“**/dist/*.min.js”]
}
}
对于文件的过滤,lint-staged 的格式如下:
{
// .js files anywhere in the project
“*.js”: “eslint”,
// .js files anywhere in the project
“**/*.js”: “eslint”,
// .js file in the src directory
“src/*.js”: “eslint”,
// .js file anywhere within and below the src directory
“src/**/*.js”: “eslint”,
}
lint-staged 提供的功能远不止于此,它只是平台,具体的格式化工具的搭配有很多,如对于图片的、样式的、.tsx、.md 等文件的。

正文完
 0