美文网首页
前端代码风格自动化(3)--Lint-staged

前端代码风格自动化(3)--Lint-staged

作者: Jonath | 来源:发表于2019-10-08 14:56 被阅读0次


    demo地址


    在我们介绍了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中配置,也可以在.lintstagedrclint-staged.config.js文件中,lint-staged的常用选项除了liners之外,还有ignoreconcurrent等,具体参考文档:

    {
      "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等文件的。

    相关文章

      网友评论

          本文标题:前端代码风格自动化(3)--Lint-staged

          本文链接:https://www.haomeiwen.com/subject/fbigyctx.html