简体   繁体   English

Javascript 和 ESLint 中的全局变量

[英]Global variables in Javascript and ESLint

I have got multiple javascript files and I have defined some global variable in a file which loads before the others.我有多个 javascript 文件,并且我在一个文件中定义了一些全局变量,这些变量在其他文件之前加载。 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".但是 ESLint 将全局变量显示为“未定义”。 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.我不想改变 ESLint 的规则,我想找到一种优雅的方式来摆脱这些错误信息。 Any clue?有什么线索吗? Thanks谢谢

I don't think hacking ESLint rules per file is a great idea.我不认为破解每个文件的 ESLint 规则是一个好主意。

You should rather define globals in .eslintrc or package.json .您应该在.eslintrcpackage.json中定义globals

For .eslintrc:对于 .eslintrc:

"globals": {
    "angular": true
}

For package.json :对于package.json

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

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

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:要使用 JavaScript 文件中的注释指定全局变量,请使用以下格式:

 /* global var1, var2 */

This defines two global variables, var1 and var2 .这定义了两个全局变量var1var2 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:如果您想选择性地指定这些全局变量不应该被写入(只读),那么您可以为每个变量设置一个 false 标志:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM