husky;lint-staged;eslint配置&原理;eslint规则开发。

摘要&心得

  • eslint
    • eslint配置文件中的extends字段代表额外开启的规则。
      • eslint:recommended
      • Google JavaScript Style Guide
      • Airbnb JavaScript Style Guide
    • ESLint 是基于静态语法分析(AST)进行工作的
    • 采用事件发布订阅模式,为所有规则的选择器添加监听事件
  • husky & lint-staged

    • husky 就是 Git 的一个钩子,在 Git 进行到某一时段时,可以交给开发者完成某些特定的操作。
    • 在整个项目上运行 Lint 会很慢,我们一般只想对更改的文件进行检查,此时就需要使用到 lint-staged
      1. "scripts": {
      2. "lint": "eslint --debug src/",
      3. "lint:write": "eslint --debug src/ --fix",
      4. "prettier": "prettier --write src/**/*.js"
      5. },
      6. "husky": {
      7. "hooks": {
      8. "pre-commit": "lint-staged"
      9. }
      10. },
      11. "lint-staged": {
      12. "*.(js|jsx)": ["npm run lint:write", "npm run prettier", "git add"]
      13. },

      eslint规则开发

      1. module.exports = {
      2. meta: {
      3. docs: {
      4. description: '禁止块级注释',
      5. category: 'Stylistic Issues',
      6. recommended: true
      7. }
      8. },
      9. create (context) {
      10. const sourceCode = context.getSourceCode()
      11. return {
      12. Program () {
      13. const comments = sourceCode.getAllComments()
      14. const blockComments = comments.filter(({ type }) => type === 'Block')
      15. blockComments.length && context.report({
      16. message: 'No block comments'
      17. })
      18. }
      19. }
      20. }
      21. }
  • 一条规则就是一个 node 模块,它由 meta 和 create 组成。

    • meta 包含了该条规则的文档描述
    • create 接受一个 context 参数,返回一个对象