How can I get ESLint to lint HTML files in VSCode?

Alex McDermott picture Alex McDermott · Jan 11, 2019 · Viewed 15.2k times · Source

I have a Javascript browser project split over multiple files and can't get ESLint to lint the script tags of my HTML file under the same global scope so that declarations and calls of classes and functions in one file are recognised in another.

Here is my project structure:

project structure

This is the contents of foo.js:

sayHello();

and bar.js:

function sayHello() {
  console.log('Hello');
}

And I have linked them both in the HTML file:

<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="main.css">
    <script src="libraries/bar.js" type="text/javascript"></script>
    <script src="foo.js" type="text/javascript"></script>
  </head>
  <body>
  </body>
</html>

I thought that the solution to this was to use the eslint-plugin-html package but have tried to configure it with no luck. These are the packages I've installed locally to the project:

Alexs-MacBook-Pro:Demo alexmcdermott$ npm list --depth=0
[email protected] /Users/alexmcdermott/GitHub/Demo
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

I'm using the VSCode editor but have also had the same problem in the terminal:

Alexs-MacBook-Pro:Demo alexmcdermott$ npx eslint --ext .js,.html .

/Users/alexmcdermott/GitHub/Demo/foo.js
  1:1  error  'sayHello' is not defined  no-undef

/Users/alexmcdermott/GitHub/Demo/libraries/bar.js
  1:10  error    'sayHello' is defined but never used  no-unused-vars
  2:3   warning  Unexpected console statement          no-console

✖ 3 problems (2 errors, 1 warning)

and the same in VSCode:

vscode error

This is my ESLint config:

{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": "airbnb-base",
    "plugins": [ "html" ]
}

and I've also configured VSCode to run ESLint on HTML files with these options in my VSCode user settings:

{
    "eslint.autoFixOnSave": true,
    "eslint.options": {
        "extensions": [ ".js", ".html" ]
    },
    "eslint.validate": [
        "javascript",
        {
            "language": "html",
            "autoFix": true
        }
    ]
}

Although I must be doing something wrong, or am missing the point of the eslint-plugin-html? If anyone has any input as to what I'm doing wrong or how to fix this I'd greatly appreciate it as I've been stuck on this for ages. Please let me know if I need to provide more info, I'm new to this.

Answer

gman picture gman · Jan 11, 2019

I have this in <projectfolder>/.vscode/settings.json

{
  "eslint.validate": [ "javascript", "html" ]
}

I'm using an .eslintrc.js that looks like this

module.exports = {
  "env": {
    "browser": true,
    "es6": true
  },
  "plugins": [
    "eslint-plugin-html",
  ],
  "extends": "eslint:recommended",
  "rules": {
  }
};

I have lots of rules defined but didn't paste them above

Result:

enter image description here