eslint-plugin-no-restricted-globals-scope-aware
v1.0.0
Published
ESLint rule to restrict globals with proper scope awareness, working around TypeScript namespace declarations
Maintainers
Readme
eslint-plugin-no-restricted-globals-scope-aware
ESLint rule to restrict globals with proper scope awareness. Unlike the built-in no-restricted-globals, this rule correctly handles cases where TypeScript namespace declarations confuse ESLint's scope analysis.
The Problem
When you have TypeScript type declarations like:
declare global {
namespace foobar { ... }
}The built-in no-restricted-globals rule won't trigger because ESLint sees foobar as "defined" by the namespace declaration.
The Solution
This plugin uses ESLint's scope analysis to check if there's an actual local variable declaration (with an initializer). This allows you to enforce a pattern where direct global access is prohibited, but access through a local variable is allowed.
The Wrapper Pattern
Create a simple wrapper function that returns the global:
// getFoobar.ts
export function getFoobar(): typeof foobar {
return foobar; // eslint-disable-line no-restricted-globals-scope-aware/no-restricted-globals-scope-aware
}Then in your code, use the wrapper to create a local variable:
import { getFoobar } from "./getFoobar";
const foobar = getFoobar();
// Now foobar.doSomething() won't trigger the rule
// because 'foobar' refers to the local variable, not the global
foobar.doSomething();This pattern:
- Centralizes global access to a single location (easier to mock/test)
- Makes dependencies explicit via imports
- Allows the linter to catch accidental direct global usage
Installation
npm install eslint-plugin-no-restricted-globals-scope-aware --save-devUsage
Add to your .eslintrc:
{
"plugins": ["no-restricted-globals-scope-aware"],
"rules": {
"no-restricted-globals-scope-aware/no-restricted-globals-scope-aware": [
"warn",
{ "name": "foobar", "message": "Use const foobar = getFoobar(); instead" },
"someOtherGlobal"
]
}
}Options
The rule accepts an array of restricted global names. Each item can be:
- A string (the global name)
- An object with
nameand optionalmessageproperties
License
MIT
