【问题标题】:Eslint determine globals from another fileEslint 从另一个文件中确定全局变量
【发布时间】:2017-04-25 01:12:09
【问题描述】:

我正在尝试设置 ESLint,使其在 linting 实际目标文件之前解析全局声明文件,这样我就不必将所有确实是全局的函数和变量声明为全局,但让解析器弄清楚:

在 some_module.js 中:

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

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

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

那么我如何告诉 ESlint 在确定以下事实时包含 global.js:

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

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

/*global glob_action*/

我想做这样的事情:

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

有可能吗?怎么样?

【问题讨论】:

标签: javascript eslint


【解决方案1】:

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

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

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

然后您需要将它导入到您的 some_module.js 中才能使用它:

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

// ...

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

这样 eslint 就不会报错了。

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

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

然后像这样在您的文件中访问它们:

globals.glob_action("foobar");

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

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2021-10-29
    相关资源
    最近更新 更多