I've got some js code that, during tests gets loaded in multiple parts, and gets concatenated and uglified for prod.
I have a config file that defines a variable myConfig
and have the business-logic script, that expects myConfig
to be set and globally available.
This is working fine, and there are no errors during dev or prod.
The problem is that I'd like to use a no-undef
eslint rule to catch other variables and function from missing declarations. So I'm looking for ways to define a set of expected variables.
Is there a way to define such variables?
From the rule documentation:
Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a
/*global ...*/
comment, or specified in theglobals
key in the configuration file. A common use case for these is if you intentionally use globals that are defined elsewhere (e.g. in a script sourced from HTML).
Further,
Specifying Globals
The no-undef rule will warn on variables that are accessed but not defined within the same file. If you are using global variables inside of a file then it’s worthwhile to define those globals so that ESLint will not warn about their usage. You can define global variables either using comments inside of a file or in the configuration file.
To specify globals using a comment inside of your JavaScript file, use the following format:
/* global var1, var2 */
This defines two global variables, var1 and var2. If you want to optionally specify that these global variables should never be written to (only read), then you can set each with a false flag:
/* global var1:false, var2:false */
To configure global variables inside of a configuration file, use the
globals
key and indicate the global variables you want to use. Set each global variable name equal totrue
to allow the variable to be overwritten orfalse
to disallow overwriting. For example:{ "globals": { "var1": true, "var2": false } }
And in YAML:
--- globals: var1: true var2: false
These examples allow
var1
to be overwritten in your code, but disallow it forvar2
.