oxc-project/oxc · error · OxcDiagnostic

"return" should be used inside a function.

Error message

"return" should be used inside a function.

What it means

Diagnostic from the unicorn/prefer-module lint rule. It fires when a top-level `return` statement is found outside any function — a CommonJS idiom used to stop module execution that is illegal or meaningless in ES modules. The flagged input is the top-level return statement. It is a lint error for module code, not a runtime exception.

Source

Thrown at crates/oxc_linter/src/rules/unicorn/prefer_module.rs:21

use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

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

const COMMON_JS_GLOBALS: [&str; 5] = ["exports", "require", "module", "__filename", "__dirname"];

fn use_strict_directive_diagnostic(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn(r#"Do not use "use strict" directive."#)
        .with_help("ES modules are always strict mode, so this directive is redundant.")
        .with_label(span)
}

fn global_return_diagnostic(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn(r#""return" should be used inside a function."#).with_label(span)
}

fn common_js_global_diagnostic(span: Span, name: &str) -> OxcDiagnostic {
    OxcDiagnostic::warn(format!(r#"Do not use "{name}"."#))
        .with_help("Prefer ES modules over CommonJS globals.")
        .with_label(span)
}

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

declare_oxc_lint!(
    /// ### What it does
    ///
    /// Prefer JavaScript modules (ESM) over CommonJS.
    ///
    /// ### Why is this bad?
    ///

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Wrap the early-exit logic in a function, or invert the condition with an `if`
  2. Replace the top-level `return` with an `if` guard around the remaining code
  3. Restructure the module body so no early top-level exit is needed
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/oxc_linter/src/rules/unicorn/prefer_module.rs:21 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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