oxc-project/oxc · warning · OxcDiagnostic

Unexpected use of `new` operator with `require`

Error message

Unexpected use of `new` operator with `require`

What it means

Diagnostic from oxlint rule node/no-new-require (restriction category). It flags `new require(...)`: using the require function as a constructor reads as a mistake and behaves surprisingly — the construct invocation runs require with a fresh `this`, and only 'works' when module.exports is an object (constructor-return override); when the module exports a primitive you silently get an unrelated empty object instead of the export.

Source

Thrown at crates/oxc_linter/src/rules/node/no_new_require.rs:9

use oxc_ast::AstKind;
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

use crate::{AstNode, context::LintContext, rule::Rule};

fn no_new_require(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn("Unexpected use of `new` operator with `require`")
        .with_help("Separate `require()` from `new` operator")
        .with_label(span)
}

#[derive(Debug, Default, Clone)]
pub struct NoNewRequire;

declare_oxc_lint!(
    /// ### What it does
    ///
    /// Warn about calling `new` on `require`.
    ///
    /// ### Why is this bad?
    ///
    /// The `require` function is used to include modules and might return a constructor. As this
    /// is not always the case this can be confusing.
    ///
    /// ### Examples

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Require first, construct second: 'const Store = require("./store"); const s = new Store();'
  2. For namespaced exports: 'const EventEmitter = require("events").EventEmitter; const e = new EventEmitter();'
  3. If the pattern is truly intentional and vetted, disable inline: // oxlint-disable-next-line node/no-new-require

Example fix

// before
const EventEmitter = new require('events').EventEmitter;

// after
const EventEmitter = require('events').EventEmitter;
Defensive patterns

Strategy: validation

Validate before calling

// .oxlintrc.json
"rules": { "node/no-new-require": "error" }

npx oxlint -c .oxlintrc.json --deny-warning .

Prevention

When it happens

Trigger: A NewExpression whose callee is the bare identifier require — e.g. const store = new require('./store');. Note the frequently-seen form new (require('events')).EventEmitter() does NOT fire because the callee there is a parenthesized member expression, not the require identifier itself.

Common situations: Copy-paste from old snippets that wrote new require('events').EventEmitter (missing parens); beginners assuming require is a class constructor; intent was usually 'require the exported class, then construct it'.

Related errors


AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20). Data as JSON: /api/errors/7296d6ab51f223b1. Report an issue: GitHub.