Handling global variables in ESLint
Include code for declaring global variables in an ESLint configuration file to prevent no-undef rule from triggering.
/* .eslintrc.js (or .eslintrc.json) configuration file */
module.exports = {
// ... other ESLint settings ...
"globals": {
"myGlobalVariable": "readonly" // Declare a global variable called myGlobalVariable
// "writable" could be used if the variable should be able to be overwritten
}
};
This is the content for the ESLint configuration file where 'myGlobalVariable' is declared. This variable can then be used within your JavaScript files without ESLint flagging it as undefined ('no-undef' rule). The value 'readonly' indicates that the variable should not be reassigned in your code, while 'writable' would allow reassignment.
// JavaScript file using the global variable
function useGlobalVar() {
console.log(myGlobalVariable); // Access the global variable without ESLint error
}
useGlobalVar();
This is a JavaScript function that logs the value of 'myGlobalVariable' to the console. Since 'myGlobalVariable' is declared in the ESLint configuration file as a global variable, ESLint will not trigger the 'no-undef' rule when this variable is used.