Global variables in Javascript and ESLint

75,923

Solution 1

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

Solution 2

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.

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 should never be written to (only read), then you can set each with a false flag:

/* global var1:false, var2:false */

http://eslint.org/docs/2.0.0/user-guide/configuring#specifying-globals

Share:
75,923
marco_sap
Author by

marco_sap

Updated on April 28, 2021

Comments

  • marco_sap
    marco_sap about 3 years

    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

  • RedSparr0w
    RedSparr0w over 6 years
    It may be worth noting that you set the global variable to true if you can assign the variable to something else and false if it shouldn't be reassigned.
  • Romain G
    Romain G about 6 years
    Linking documentation is a virtue that is much appreciated on stackoverflow answers.
  • v-andrew
    v-andrew about 6 years
    @RomainG there is already link below ;) But I'll add one for you
  • Joshua Pinter
    Joshua Pinter almost 3 years
    Moreover, you can actually make them "readonly" or "writable".