在咱们介绍了Husky、Commitlint以后,来看一个前端文件过滤的工具Lint-staged,代码的格式化确定会涉及到文件系统,通常工具会首先读取文件,格式化操做以后,从新写入。对于较大型的项目,文件众多,首先遇到的就是性能问题,虽然如Eslint之类的也有文件过滤配置,但毕竟仍是对于匹配文件的全量遍历,如全量的.js
文件,基本达不到性能要求,有时还会误格式化其余同窗的代码,所以咱们引入Lint-staged,一个仅仅过滤出Git代码暂存区文件(被committed的文件)的工具。css
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
,命令,前者的的目的是格式化,后者是对格式化以后的代码从新提交。git
除了在package.json
中配置,也能够在.lintstagedrc
、lint-staged.config.js
文件中,lint-staged
的经常使用选项除了liners
以外,还有ignore
、concurrent
等,具体参考文档:npm
{ "lint-staged": { "linters": { "*.{js,scss}": ["some command", "git add"] }, "ignore": ["**/dist/*.min.js"] } }
对于文件的过滤,lint-staged
的格式以下:json
{ // .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
等文件的。工具