【问题标题】:How do I share global javascript variables among multiple files prior to compiling?如何在编译之前在多个文件之间共享全局 javascript 变量?
【发布时间】:2018-01-22 18:20:04
【问题描述】:

当有多个文件将被编译为共享全局变量/函数的单个文件时,处理 linting 的最佳方法是什么。例如:

file_1.js:

{
const my_flag = 1;
}

file_2.js:

{
  if (my_flag) {
  // etc.

当两个文件编译合并后,就没有问题了。但是 file_1.js 会引发与未使用变量相关的 linting 错误,而 file_2.js 会引发与未定义变量相关的 linting 错误。

我知道我可以忽略与问题相关的特定行,但这违背了整理文件的目的。在 linting 过程中,在文件之间共享信息的最佳方式是什么?

【问题讨论】:

  • 为什么是 {} 括号?还有你所说的 compiled and combined 是什么意思?将两个文件的内容复制粘贴到第三个文件中?也许您想考虑使用模块和模块捆绑器。

标签: javascript eslint gulp-eslint


【解决方案1】:

使用eslint,您可以告诉脚本变量是全局变量:

/* global my_flag */

将此行放在第二个文件中使用my_flag 之前(通常这是文件的第一行)。这将避免关于 undefined 变量 my_flag 的 linting 错误

【讨论】:

    【解决方案2】:

    .eslintrc 配置文件允许命名 globals 解决了这个问题:

    "globals": {
      "my_global": true,
      "another_global": true,
      "third_global": true
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 2015-09-21
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多