Utility functions for managing ESLint configurations, globals conversion, and cross-environment compatibility. These helpers provide essential functionality for configuration management and module loading.
Generic utility function for converting sources to ESLint globals object with proper typing.
function getGlobals<
T extends Record<string, unknown> | string[],
G extends Record<string, boolean>,
R extends G = G & Record<T extends Array<infer R> ? R : keyof T, false>
>(sources: T, initialGlobals?: G): R;The getGlobals function:
false (read-only)initialGlobals parameterUsage Examples:
import { getGlobals } from "eslint-plugin-mdx";
// From array of strings
const globals1 = getGlobals(['React', 'process', 'global']);
// Result: { React: false, process: false, global: false }
// From object keys
const globals2 = getGlobals({ React: 'any', process: 'any' });
// Result: { React: false, process: false }
// With initial globals
const globals3 = getGlobals(['React'], { window: true });
// Result: { window: true, React: false }
// In ESLint config
export default [
{
languageOptions: {
globals: getGlobals(['React', 'JSX'])
}
}
];Cross-environment CommonJS require function for ESM compatibility.
declare const cjsRequire: CjsRequire;
interface CjsRequire {
<T = any>(id: string): T;
resolve(id: string): string;
}The cjsRequire function:
require functionality in ESM modulescreateRequire when available (Node.js ESM)require in CommonJS environmentsUsage Examples:
import { cjsRequire } from "eslint-plugin-mdx";
// Load a CommonJS module
const packageJson = cjsRequire('./package.json');
// Resolve module path
const resolvedPath = cjsRequire.resolve('eslint');
// Load optional dependencies
try {
const prettier = cjsRequire('prettier');
// Use prettier if available
} catch {
// Handle missing dependency
}// Generic helper types
type ArrayElement<T> = T extends Array<infer U> ? U : never;
type ObjectKeys<T> = T extends Record<string, unknown> ? keyof T : never;
// Globals type mapping
type GlobalsFromArray<T extends string[]> = Record<ArrayElement<T>, false>;
type GlobalsFromObject<T extends Record<string, unknown>> = Record<keyof T, false>;
// CommonJS require interface
interface CjsRequire {
<T = any>(id: string): T;
resolve(id: string): string;
}The helpers are designed to work across different JavaScript environments:
import.meta.url and createRequirerequireAdvanced Usage:
// Custom globals with type safety
interface CustomGlobals {
myGlobal: boolean;
anotherGlobal: boolean;
}
const customGlobals: CustomGlobals = {
myGlobal: true,
anotherGlobal: false
};
// Merge with library globals
const allGlobals = getGlobals(
['React', 'process'],
customGlobals
);
// Type: CustomGlobals & { React: false, process: false }