Eslint从另一个文件确定全局变量 [英] Eslint determine globals from another file

查看:172
本文介绍了Eslint从另一个文件确定全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以这样一种方式设置ESLint:它在插入实际目标文件之前先解析一个globals声明文件,这样我就不必将确实是globals的所有函数和变量声明为globals,但让解析器指出:

I'm trying to set up ESLint in such a way that it parses a globals declaration file before linting the actual target file, so that I don't have to declare as globals all the functions and variables that are indeed globals, but letting the parser figure that out:

some_module.js 中:

function do_something() {
  if (glob_action("foobar")) {
     ... something something ...
  }
}

globals.js 中,我有一组实用程序和全局变量:

While in globals.js I have a set of utilities and global variables:

function glob_action(x) {
   ... something something ...
}

所以我如何告诉ESlint包括global.js来确定以下事实:

So how can I tell to ESlint to include global.js in determining the fact that:

76:3  error  'glob_action' is not defined  no-undef

实际上并不是未定义的,但我不想将其列为全局变量:

is not actually undefined, but I do NOT want to list it as global:

/*global glob_action*/

我想执行以下操作:

/*eslint include "../globa.js"*/

有可能吗?

推荐答案

我强烈建议您使用导入/导出机制,而不是让每个成员都可以全局访问。

I highly recommend using the import/export mechanism, instead of having every member global accessible.

使用ES6模块时,可以像下面这样在 globals.js 中导出函数:

When working with ES6 modules, you can export your functions in your globals.js like so:

export function glob_action(x) {
  ... something something ...
}

然后您需要将其导入到 some_module.js 中以使用它:

You then need to import it in your some_module.js to use it:

import { glob_action } from './globals.js';

// ...

function do_something() {
  if (glob_action("foobar")) {
     ... something something ...
  }
}

这样eslint不会抛出错误。

This way eslint will not throw an error.

您将需要在每个要使用它们的模块中导入资源,因此它并不像您要求的那样通用,但是这样您就不会污染您的全局名称空间。
另外,您不需要手动导入每个函数,因为您可以使用以下命令导入整个模块:

You will need to import the resources in every module where you want to use them, so it's not quite as generic as you requested it, but this way you will not polute your global namespace. Also you do not need to import every single function manually, as you can import the whole module using:

import * as globals from './globals.js'

,然后像这样访问它们:

and then access them in your file like so:

globals.glob_action("foobar");

请参阅: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/import 有关导入成员的更多信息来自其他模块。

See: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/import for more information on importing members from other modules.

这篇关于Eslint从另一个文件确定全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆