philk
philk

Reputation: 2140

Custom eslint rule throws with unexpected reserved word

I have this code

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

Properly installed as local file package. eslint loads it but fails with

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)

The stacktrace is not very helpful. The rule itself validates just fine with eslint.

Upvotes: 0

Views: 684

Answers (1)

philk
philk

Reputation: 2140

The errors where the const identifiers. This is the correct rule file:

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

However, the error reporting of eslint could be better. Will file a report over there.

Upvotes: 1

Related Questions