Skip to content

Commit

Permalink
fix(linter): handle user variables correctly for import/no_commonjs (#…
Browse files Browse the repository at this point in the history
…7316)

test case found in `typescript/no-require-imports`
  • Loading branch information
pumano authored Nov 19, 2024
1 parent 1d9f528 commit bc0e72c
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion crates/oxc_linter/src/rules/import/no_commonjs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use oxc_ast::{
use crate::{context::LintContext, rule::Rule, AstNode};

fn no_commonjs_diagnostic(span: Span, name: &str, actual: &str) -> OxcDiagnostic {
// See <https://oxc.rs/docs/contribute/linter/adding-rules.html#diagnostics> for details
OxcDiagnostic::warn(format!("Expected {name} instead of {actual}"))
.with_help("Do not use CommonJS `require` calls and `module.exports` or `exports.*`")
.with_label(span)
Expand Down Expand Up @@ -214,6 +213,10 @@ impl Rule for NoCommonjs {
return;
}

if ctx.scopes().find_binding(ctx.scopes().root_scope_id(), "require").is_some() {
return;
}

if let Argument::TemplateLiteral(template_literal) = &call_expr.arguments[0] {
if template_literal.expressions.len() != 0 {
return;
Expand Down Expand Up @@ -299,6 +302,15 @@ fn test() {
Some(json!([{ "allowRequire": false }])),
),
(r#"try { require("x") } catch (error) {}"#, None),
// covers user variables
(
"
import { createRequire } from 'module';
const require = createRequire();
require('remark-preset-prettier');
",
None,
),
];

let fail = vec![
Expand Down

0 comments on commit bc0e72c

Please sign in to comment.