ESLint InterlaceESLint Interlace
Plugin: modernizationRules

prefer-event-target

ESLint rule documentation for prefer-event-target

📡 Live from GitHub — This documentation is fetched directly from prefer-event-target.md and cached for 6 hours.

Keywords: EventTarget, EventEmitter, browser, Node.js, events, ESLint rule, LLM-optimized

Prefer EventTarget over EventEmitter for isomorphic code

Prefer EventTarget over EventEmitter for isomorphic code. This rule is part of eslint-plugin-modernization.

Quick Summary

AspectDetails
SeverityWarning (compatibility)
Auto-Fix❌ No (different API)
CategoryModernization
ESLint MCP✅ Optimized for ESLint MCP integration
Best ForIsomorphic code, browser compatibility

Rule Details

EventTarget is available in both browsers and Node.js (v14.5+), while EventEmitter is Node.js-specific.

Why This Matters

IssueImpactSolution
🌐 Browser supportEventEmitter not in browsersUse EventTarget
📦 Bundle sizePolyfills neededNative API
🔄 Isomorphic codeDifferent APIs per environmentStandardize on EventTarget

Examples

❌ Incorrect

import { EventEmitter } from 'events';

class MyEmitter extends EventEmitter {
  emit(event: string) {
    super.emit(event);
  }
}

✅ Correct

class MyEmitter extends EventTarget {
  dispatch(type: string, detail?: unknown) {
    this.dispatchEvent(new CustomEvent(type, { detail }));
  }
}

// Usage
const emitter = new MyEmitter();
emitter.addEventListener('change', (e) => console.log(e));
emitter.dispatch('change', { value: 42 });

Configuration Examples

Basic Usage

{
  rules: {
    'architecture/prefer-event-target': 'warn'
  }
}

Further Reading

Known False Negatives

The following patterns are not detected due to static analysis limitations:

Dynamic Variable References

Why: Static analysis cannot trace values stored in variables or passed through function parameters.

// ❌ NOT DETECTED - Value from variable
const value = externalSource();
processValue(value); // Variable origin not tracked

Mitigation: Implement runtime validation and review code manually. Consider using TypeScript branded types for validated inputs.

Imported Values

Why: When values come from imports, the rule cannot analyze their origin or construction.

// ❌ NOT DETECTED - Value from import
import { getValue } from './helpers';
processValue(getValue()); // Cross-file not tracked

Mitigation: Ensure imported values follow the same constraints. Use TypeScript for type safety.

On this page

No Headings