BenoitZugmeyer / eslint-plugin-html

An ESLint plugin to extract and lint scripts from HTML files.
ISC License
430 stars 51 forks source link

`no_unused_vars` triggered wrongly #61

Closed jonathanGB closed 4 years ago

jonathanGB commented 7 years ago

Hi,

I have a file with the following structure, in which I get the following error:

'checkSubmit' is defined but never used

<form onsubmit="return checkSubmit(1)">
  ...
</form>

<script>
  function checkSubmit(num) {
    ...
  }
</script>

Clearly, checkSubmit is used as a listener. Maybe the html is ignored by the plugin, even though it may have an impact on rules like this one.

Thanks!

BenoitZugmeyer commented 7 years ago

Hi, thanks for the report. Sadly, I have no idea how linting JS in HTML attributes could work... I can't think of a way to feed it to ESLint. I'm open to suggestions.

hsxfjames commented 7 years ago

How about parse onXXX attributes and transform into a fake JS segment? Then hack the messages from ESLint.

armano2 commented 5 years ago

@BenoitZugmeyer To parse attributes you have to use something like this

  const parser = new htmlparser.Parser(
    {
...
      onattribute(name, value) {
        const cdata = []
        if (/^javascript:/i.test(value)) {
          const end = parser.endIndex - 1 // idk if quote is included
          chunks.push({
            type: "inlineScript",
            start: end - value.length + 10, // not sure about those values
            end,
            cdata,
          })
        } else if (/^on/i.test(name)) {
          const end = parser.endIndex - 1 // idk if quote is included
          chunks.push({
            type: "inlineScript",
            start: end - value.length,
            end,
            cdata,
          })
        }
      },
...

after parsing html event attributes you will have to make rule thats triggers

context.markVariableAsUsed(name)

see https://eslint.org/docs/developer-guide/working-with-rules#the-context-object

BenoitZugmeyer commented 4 years ago

Superseded by #123