问题
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?
回答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.
来源:https://stackoverflow.com/questions/41062416/eslint-determine-globals-from-another-file