我有这个代码

var astUtils = require("eslint/lib/ast-utils")

module.exports = function(context) {
  const selfConfigRegEx = /\bno-best-before-comments\b/
  const now = new Date()
  const regex = /BEST-?BEFORE (\d{4}-\d{2}-\d{2})/ig

  function checkBefore(node) {
    if (astUtils.isDirectiveComment(node) && selfConfigRegEx.test(node.value)) {
      return
    }

    const bestBeforeDate = new Date(regex.match(node.value)[0])
    if (bestBeforeDate > now) {
      context.report(node, "BEST-BEFORE is expired since " + bestBeforeDate)
    }
  }

  return {
    "BlockComment": checkBefore,
    "LineComment": checkBefore
  }
}


正确安装为本地文件包。 eslint加载它,但失败

SyntaxError: Failed to load plugin my-internal: Unexpected reserved word
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (c:\dev\projects\app\node_modules\eslint-plugin-my-internal\index.js:2:18)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)


stacktrace不是很有帮助。规则本身可以通过eslint进行验证。

最佳答案

const标识符所在的错误。这是正确的规则文件:

/** eslint-disable semi */
"use strict"

var astUtils = require("eslint/lib/ast-utils")

module.exports = function(context) {
  var selfConfigRegEx = /\bno-best-before-comments\b/
  var now = new Date()
  var regex = /BEST-?BEFORE:?\s*(\d{4}-\d{1,2}-\d{1,2})/ig

  function checkBefore(node) {
    if (astUtils.isDirectiveComment(node) && selfConfigRegEx.test(node.value)) {
      return
    }

    var dateString = regex.exec(node.value)[1]
    var bestBeforeDate = new Date(dateString)
    if (bestBeforeDate < now) {
      context.report(node, "BEST-BEFORE expired since " + dateString)
    }
  }

  return {
    "BlockComment": checkBefore,
    "LineComment": checkBefore
  }
}

module.exports.schema = [
    // JSON Schema for rule options goes here
]


但是,eslint的错误报告可能会更好。将在那边提交报告。

关于javascript - 自定义eslint规则引发意外保留字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35850285/

10-16 20:51