From bc0e72c1e286d9015c8ab60ef0200761ab41e7e7 Mon Sep 17 00:00:00 2001 From: Dmitry Zakharov Date: Tue, 19 Nov 2024 04:23:16 +0300 Subject: [PATCH] fix(linter): handle user variables correctly for import/no_commonjs (#7316) test case found in `typescript/no-require-imports` --- crates/oxc_linter/src/rules/import/no_commonjs.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/oxc_linter/src/rules/import/no_commonjs.rs b/crates/oxc_linter/src/rules/import/no_commonjs.rs index 0dc315102..8dc2f16c5 100644 --- a/crates/oxc_linter/src/rules/import/no_commonjs.rs +++ b/crates/oxc_linter/src/rules/import/no_commonjs.rs @@ -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 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) @@ -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; @@ -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![