16

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:

In some_module.js:

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

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

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

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*/

I would like to do something like:

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

Is it possible? How?

Johnny
  • 1,770
  • 12
  • 16
  • Have you considered specifying them in an [`.eslintrc` file](http://eslint.org/docs/user-guide/configuring#specifying-globals)? – cartant Dec 10 '16 at 02:28
  • 2
    Obviously yes, but this way I have to maintain two lists of globals. I don't want to be enslaved maintaining a support file. – Johnny Dec 10 '16 at 19:34
  • 2
    Related question: [Global variables in Javascript and ESLint](https://stackoverflow.com/questions/41552041/global-variables-in-javascript-and-eslint) – joeytwiddle Jul 11 '17 at 06:16

1 Answers1

1

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

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

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

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 ...
  }
}

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");

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

Cr45hCode
  • 52
  • 3