[AST Eslint] No console with schema options && isPrimitive

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[AST Eslint] No console with schema options && isPrimitive相关的知识,希望对你有一定的参考价值。

// eslint exercise 4 (no-console)
// When you‘re finished with this exercise, run
//   "npm start exercise.eslint.5"
//   to move on to the next exercise

const disallowedMethods = [log, info, warn, error, dir]

module.exports = {
  meta: {
    schema: [
      {
        type: object,
        properties: {
          allowedMethods: {
            type: array,
            items: {
              enum: [log, info, warn, error, dir],
            },
            minItems: 1,
            uniqueItems: true,
          },
        },
      },
    ],
  },
  create(context) {
    const config = context.options[0] || {}
    const allowedMethods = config.allowedMethods || []
    return {
      Identifier(node) {
        if (
          !looksLike(node, {
            name: console,
            parent: {
              type: MemberExpression,
              parent: {type: CallExpression},
              property: {
                name: val =>
                  !allowedMethods.includes(val) &&
                  disallowedMethods.includes(val),
              },
            },
          })
        ) {
          return
        }
        context.report({
          node: node.parent.property,
          message: Using console is not allowed,
        })
      },
    }
  },
}

function looksLike(a, b) {
  return (
    a &&
    b &&
    Object.keys(b).every(bKey => {
      const bVal = b[bKey]
      const aVal = a[bKey]
      if (typeof bVal === function) {
        return bVal(aVal)
      }
      return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal)
    })
  )
}

function isPrimitive(val) {
  return val == null || /^[sbn]/.test(typeof val)
}

 

// eslint exercise 4 (no-console)
// When you‘re finished with this exercise, run
//   "npm start exercise.eslint.5"
//   to move on to the next exercise

const {RuleTester} = require(eslint)
const rule = require(./no-console)

const ruleTester = new RuleTester()
ruleTester.run(no-console, rule, {
  valid: [
    info(),
    console,
    console.log,
    console.baz(),
    {code: console.warn(), options: [{allowedMethods: [warn]}]},
  ],
  invalid: [
    invalid(console.log()),
    invalid(console.info()),
    invalid(console.warn()),
  ],
})

function invalid(code) {
  return {
    code,
    errors: [{message: Using console is not allowed}],
  }
}

 

以上是关于[AST Eslint] No console with schema options && isPrimitive的主要内容,如果未能解决你的问题,请参考以下文章

[AST ESlint] Prevent Console log, edge case, variable reference

[Javascript AST] 2. Write a simple ESLint rule

前端手把手教你用TypeScript写一个简单的eslint插件

[Javascript AST] 4. Continue: Report ESLint error

无法使用 eslint cli 启用无控制台

如何将 typescript-eslint 规则添加到 eslint