Skip to main content

react_auditor/rules/performance/
no_large_libraries.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7const HEAVY_LIBS: &[(&str, &str)] = &[
8    ("moment", "Use `date-fns` or `dayjs` instead of `moment`"),
9    (
10        "lodash",
11        "Use native array/object methods or `rambda` instead of `lodash`",
12    ),
13    (
14        "underscore",
15        "Use native array/object methods instead of `underscore`",
16    ),
17    (
18        "jquery",
19        "Avoid jQuery in React projects — use React refs and state",
20    ),
21    (
22        "axios",
23        "Prefer `fetch` or `ky` over `axios` for HTTP requests",
24    ),
25];
26
27pub struct NoLargeLibraries;
28
29const RULE_META: RuleMeta = RuleMeta {
30    id: "no-large-libraries",
31    default_severity: Severity::Warning,
32    category: "performance",
33    description: "Avoid importing large libraries when lighter alternatives exist",
34};
35
36impl Rule for NoLargeLibraries {
37    fn meta(&self) -> &RuleMeta {
38        &RULE_META
39    }
40
41    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
42        let mut collector = LargeLibCollector {
43            findings: Vec::new(),
44            source: source_text,
45        };
46        collector.visit_program(program);
47        collector.findings
48    }
49}
50
51struct LargeLibCollector<'a> {
52    findings: Vec<RuleFinding>,
53    source: &'a str,
54}
55
56impl<'a> LargeLibCollector<'a> {
57    fn add_finding(&mut self, start: usize, msg: String) {
58        let line = self.source[..start].lines().count().max(1);
59        let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
60        self.findings.push(RuleFinding {
61            line,
62            column: col + 1,
63            message: msg,
64        });
65    }
66}
67
68impl<'a> Visit<'a> for LargeLibCollector<'a> {
69    fn visit_import_declaration(&mut self, decl: &oxc_ast::ast::ImportDeclaration<'a>) {
70        let path = decl.source.value.as_str();
71        for (lib_name, suggestion) in HEAVY_LIBS {
72            if path == *lib_name || path.starts_with(&format!("{lib_name}/")) {
73                self.add_finding(
74                    decl.span.start as usize,
75                    format!("Avoid importing `{path}`. {suggestion}"),
76                );
77            }
78        }
79    }
80}