码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-01-23 22:36:43      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:enum   cti   star   call   module   ini   let   items   start   

// 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

标签:enum   cti   star   call   module   ini   let   items   start   

原文地址:https://www.cnblogs.com/Answer1215/p/12231422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!