154

I have got multiple javascript files and I have defined some global variable in a file which loads before the others. As a consequence all of the files loaded after the first have access to the global variable. However ESLint shows the global variable as "not defined". I don't want to change the rules of ESLint and I would like to find an elegant way to get rid of these error messages. Any clue? Thanks

marco_sap
  • 1,739
  • 2
  • 12
  • 12
  • 4
    `->` http://eslint.org/docs/user-guide/configuring#specifying-globals . ESLint's documentation is great IMO, you should take a look at that. – Felix Kling Jan 09 '17 at 16:12
  • _"an elegant way to get rid of these error messages"_ - personally I would prefer to remove the global variables! – phuzi May 04 '23 at 09:51

2 Answers2

186

I don't think hacking ESLint rules per file is a great idea.

You should rather define globals in .eslintrc or package.json.

For .eslintrc:

"globals": {
    "angular": true
}

For package.json:

"eslintConfig": {
    "globals": {
        "angular": true
    }
}

Check https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals

MkMan
  • 1,779
  • 1
  • 14
  • 27
v-andrew
  • 21,939
  • 6
  • 36
  • 41
152

You can add globals either per file or in your config. If you don't want to change your config, you'll have to add the used globals in every file.

From the Specifying globals ESLint docs section:

To specify globals using a comment inside of your JavaScript file, use the following format:

/* global var1, var2 */

This defines two global variables, var1 and var2. If you want to optionally specify that these global variables can be written to (rather than only being read), then you can set each with a with a "writable" flag:

/* global var1:writable, var2:writable */

Older versions of ESLint used var1:false to indicate that var1 should be read-only.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
DarkLegend
  • 1,706
  • 1
  • 11
  • 10