rspack_plugin_javascript 0.100.0-rc.3

rspack javascript plugin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
use rspack_core::{
  CachedConstDependency, ConstDependency, ImportMeta, NodeDirnameOption, NodeFilenameOption,
  NodeGlobalOption, RuntimeGlobals, RuntimeRequirementsDependency, get_context, parse_resource,
};
use rspack_error::{Diagnostic, cyan, yellow};
use rspack_util::SpanExt;
use sugar_path::SugarPath;
use swc_core::{common::Spanned, ecma::ast::Expr};
use url::Url;

use crate::{
  JavascriptParserPlugin,
  dependency::ExternalModuleDependency,
  utils::eval,
  visitors::{DestructuringAssignmentProperty, JavascriptParser},
};

const DIRNAME: &str = "__dirname";
const FILENAME: &str = "__filename";
const IMPORT_META_DIRNAME: &str = "import.meta.dirname";
const IMPORT_META_FILENAME: &str = "import.meta.filename";
const GLOBAL: &str = "global";
const MOCK_DIRNAME: &str = "/";
const MOCK_FILENAME: &str = "/index.js";

/// Represents the type of import.meta property being handled (filename or dirname)
#[derive(Clone, Copy)]
enum NodeMetaProperty {
  Filename,
  Dirname,
}

impl NodeMetaProperty {
  /// Returns the mock value for this property
  fn mock_value(&self) -> &'static str {
    match self {
      NodeMetaProperty::Filename => MOCK_FILENAME,
      NodeMetaProperty::Dirname => MOCK_DIRNAME,
    }
  }

  /// Returns the import.meta property name
  fn import_meta_name(&self) -> &'static str {
    match self {
      NodeMetaProperty::Filename => "import.meta.filename",
      NodeMetaProperty::Dirname => "import.meta.dirname",
    }
  }

  /// Returns the CJS equivalent variable name
  fn cjs_name(&self) -> &'static str {
    match self {
      NodeMetaProperty::Filename => "__filename",
      NodeMetaProperty::Dirname => "__dirname",
    }
  }

  /// Returns the warning code for this property
  fn warning_code(&self) -> &'static str {
    match self {
      NodeMetaProperty::Filename => "NODE_IMPORT_META_FILENAME",
      NodeMetaProperty::Dirname => "NODE_IMPORT_META_DIRNAME",
    }
  }

  /// Returns the warning message for this property
  fn warning_message(&self) -> String {
    match self {
      NodeMetaProperty::Filename => format!(
        "\"{}\" is used and has been mocked. Remove it from your code, or set `{}` to disable this warning.",
        yellow(&IMPORT_META_FILENAME),
        cyan(&"node.__filename")
      ),
      NodeMetaProperty::Dirname => format!(
        "\"{}\" is used and has been mocked. Remove it from your code, or set `{}` to disable this warning.",
        yellow(&IMPORT_META_DIRNAME),
        cyan(&"node.__dirname")
      ),
    }
  }

  /// Returns the runtime expression for NodeModule mode
  fn node_module_runtime_expr(&self) -> &'static str {
    match self {
      NodeMetaProperty::Filename => "__rspack_fileURLToPath(import.meta.url)",
      NodeMetaProperty::Dirname => "__rspack_dirname(__rspack_fileURLToPath(import.meta.url))",
    }
  }

  /// Returns whether dirname is disabled based on node options
  fn is_disabled(&self, node_option: &rspack_core::NodeOption) -> bool {
    match self {
      NodeMetaProperty::Filename => matches!(node_option.filename, NodeFilenameOption::False),
      NodeMetaProperty::Dirname => matches!(node_option.dirname, NodeDirnameOption::False),
    }
  }

  /// Check if the option is Mock
  fn is_mock(&self, node_option: &rspack_core::NodeOption) -> bool {
    match self {
      NodeMetaProperty::Filename => matches!(node_option.filename, NodeFilenameOption::Mock),
      NodeMetaProperty::Dirname => matches!(node_option.dirname, NodeDirnameOption::Mock),
    }
  }

  /// Check if the option is WarnMock
  fn is_warn_mock(&self, node_option: &rspack_core::NodeOption) -> bool {
    match self {
      NodeMetaProperty::Filename => matches!(node_option.filename, NodeFilenameOption::WarnMock),
      NodeMetaProperty::Dirname => matches!(node_option.dirname, NodeDirnameOption::WarnMock),
    }
  }

  /// Check if the option is True
  fn is_true(&self, node_option: &rspack_core::NodeOption) -> bool {
    match self {
      NodeMetaProperty::Filename => matches!(node_option.filename, NodeFilenameOption::True),
      NodeMetaProperty::Dirname => matches!(node_option.dirname, NodeDirnameOption::True),
    }
  }

  /// Check if the option is EvalOnly
  fn is_eval_only(&self, node_option: &rspack_core::NodeOption) -> bool {
    match self {
      NodeMetaProperty::Filename => matches!(node_option.filename, NodeFilenameOption::EvalOnly),
      NodeMetaProperty::Dirname => matches!(node_option.dirname, NodeDirnameOption::EvalOnly),
    }
  }

  /// Check if the option is NodeModule
  fn is_node_module(&self, node_option: &rspack_core::NodeOption) -> bool {
    match self {
      NodeMetaProperty::Filename => matches!(node_option.filename, NodeFilenameOption::NodeModule),
      NodeMetaProperty::Dirname => matches!(node_option.dirname, NodeDirnameOption::NodeModule),
    }
  }
}

/// Plugin for handling Node.js-specific variables like `__dirname`, `__filename`, `global`,
/// and their ESM equivalents `import.meta.dirname` and `import.meta.filename`.
///
/// This mirrors webpack's approach where NodeStuffPlugin is registered once per module type
/// with boolean flags controlling which features to handle:
/// - `handle_cjs`: handle `__dirname`, `__filename`, `global`
/// - `handle_esm`: handle `import.meta.dirname`, `import.meta.filename`
pub struct NodeStuffPlugin {
  /// When true, handle __dirname/__filename/global (CJS features)
  handle_cjs: bool,
  /// When true, handle import.meta.dirname/filename (ESM features)
  handle_esm: bool,
}

impl NodeStuffPlugin {
  pub fn new(handle_cjs: bool, handle_esm: bool) -> Self {
    Self {
      handle_cjs,
      handle_esm,
    }
  }

  /// Get the relative path value for the given property (filename or dirname)
  fn get_relative_path(parser: &JavascriptParser, property: NodeMetaProperty) -> Option<String> {
    match property {
      NodeMetaProperty::Filename => Some(
        parser
          .resource_data
          .path()?
          .as_std_path()
          .relative(&parser.compiler_options.context)
          .to_string_lossy()
          .to_string(),
      ),
      NodeMetaProperty::Dirname => Some(
        parser
          .resource_data
          .path()?
          .parent()?
          .as_std_path()
          .relative(&parser.compiler_options.context)
          .to_string_lossy()
          .to_string(),
      ),
    }
  }

  /// Get the absolute path value for node-module mode
  fn get_absolute_path(parser: &JavascriptParser, property: NodeMetaProperty) -> Option<String> {
    let path = Url::from_file_path(parser.resource_data.resource())
      .expect("should be a path")
      .to_file_path()
      .expect("should be a path");

    match property {
      NodeMetaProperty::Filename => Some(path.to_string_lossy().into_owned()),
      NodeMetaProperty::Dirname => Some(
        path
          .parent()
          .expect("should have a parent")
          .to_string_lossy()
          .into_owned(),
      ),
    }
  }

  /// Get the eval-only path value
  fn get_eval_only_path(parser: &JavascriptParser, property: NodeMetaProperty) -> Option<String> {
    match property {
      NodeMetaProperty::Filename => {
        let resource = parse_resource(parser.resource_data.path()?.as_str())?;
        Some(resource.path.to_string())
      }
      NodeMetaProperty::Dirname => Some(parser.resource_data.path()?.parent()?.to_string()),
    }
  }

  /// Add external dependencies for NodeModule mode
  fn add_node_module_dependencies(parser: &mut JavascriptParser, property: NodeMetaProperty) {
    let external_url_dep = ExternalModuleDependency::new(
      "url".to_string(),
      vec![(
        "fileURLToPath".to_string(),
        "__rspack_fileURLToPath".to_string(),
      )],
      None,
    );
    parser.add_presentational_dependency(Box::new(external_url_dep));

    if matches!(property, NodeMetaProperty::Dirname) {
      let external_path_dep = ExternalModuleDependency::new(
        "path".to_string(),
        vec![("dirname".to_string(), "__rspack_dirname".to_string())],
        None,
      );
      parser.add_presentational_dependency(Box::new(external_path_dep));
    }
  }

  fn add_cjs_node_module_dependency(
    parser: &mut JavascriptParser,
    ident_span: swc_core::common::Span,
    name: &str,
    property: NodeMetaProperty,
  ) {
    Self::add_node_module_dependencies(parser, property);
    let const_dep = CachedConstDependency::new(
      ident_span.into(),
      name.into(),
      property.node_module_runtime_expr().into(),
    );
    parser.add_presentational_dependency(Box::new(const_dep));
  }

  /// Get the evaluated value for import.meta.filename/dirname
  fn get_import_meta_eval_value(
    parser: &JavascriptParser,
    property: NodeMetaProperty,
  ) -> Option<String> {
    let node_option = parser.compiler_options.node.as_ref()?;

    if property.is_disabled(node_option) {
      return None;
    }

    if property.is_mock(node_option) || property.is_warn_mock(node_option) {
      return Some(property.mock_value().to_string());
    }

    if property.is_true(node_option) {
      return Self::get_relative_path(parser, property);
    }

    if property.is_eval_only(node_option) {
      return Self::get_eval_only_path(parser, property);
    }

    if property.is_node_module(node_option) {
      return Self::get_absolute_path(parser, property);
    }

    None
  }

  /// Get the member replacement value for import.meta.filename/dirname
  fn get_import_meta_member_replacement(
    parser: &mut JavascriptParser,
    property: NodeMetaProperty,
  ) -> Option<String> {
    let node_option = match parser.compiler_options.node.as_ref() {
      None => return Some(property.import_meta_name().to_string()),
      Some(opt) => opt,
    };

    if property.is_disabled(node_option) {
      return Some(property.import_meta_name().to_string());
    }

    if property.is_mock(node_option) {
      return Some(format!("'{}'", property.mock_value()));
    }

    if property.is_warn_mock(node_option) {
      parser.add_warning(Diagnostic::warn(
        property.warning_code().to_string(),
        property.warning_message(),
      ));
      return Some(format!("'{}'", property.mock_value()));
    }

    if property.is_true(node_option) {
      let path = Self::get_relative_path(parser, property)?;
      return Some(format!("'{path}'"));
    }

    if property.is_eval_only(node_option) {
      return Some(if parser.compiler_options.output.module {
        property.import_meta_name().to_string()
      } else {
        property.cjs_name().to_string()
      });
    }

    if property.is_node_module(node_option) {
      // Check if native import.meta.dirname/filename is supported
      if parser.compiler_options.output.module
        && parser
          .compiler_options
          .output
          .environment
          .supports_import_meta_dirname_and_filename()
      {
        // Keep as import.meta.filename/dirname - runtime supports it
        return Some(property.import_meta_name().to_string());
      }
      Self::add_node_module_dependencies(parser, property);
      return Some(property.node_module_runtime_expr().to_string());
    }

    None
  }

  /// Get the destructuring replacement value for import.meta.filename/dirname
  fn get_import_meta_destructuring_value(
    parser: &mut JavascriptParser,
    property: NodeMetaProperty,
  ) -> Option<String> {
    let node_option = match parser.compiler_options.node.as_ref() {
      None => return Some(property.import_meta_name().to_string()),
      Some(opt) => opt,
    };

    if property.is_disabled(node_option) {
      return Some(property.import_meta_name().to_string());
    }

    if property.is_mock(node_option) {
      return Some(format!("\"{}\"", property.mock_value()));
    }

    if property.is_warn_mock(node_option) {
      parser.add_warning(Diagnostic::warn(
        property.warning_code().to_string(),
        property.warning_message(),
      ));
      return Some(format!("\"{}\"", property.mock_value()));
    }

    if property.is_true(node_option) {
      let path = Self::get_relative_path(parser, property)?;
      return Some(format!("\"{path}\""));
    }

    if property.is_eval_only(node_option) {
      return Some(if parser.compiler_options.output.module {
        property.import_meta_name().to_string()
      } else {
        property.cjs_name().to_string()
      });
    }

    if property.is_node_module(node_option) {
      // Check if native import.meta.dirname/filename is supported
      if parser.compiler_options.output.module
        && parser
          .compiler_options
          .output
          .environment
          .supports_import_meta_dirname_and_filename()
      {
        return Some(property.import_meta_name().to_string());
      }
      Self::add_node_module_dependencies(parser, property);
      return Some(property.node_module_runtime_expr().to_string());
    }

    None
  }
}

#[rspack_macros::implemented_javascript_parser_hooks]
impl JavascriptParserPlugin for NodeStuffPlugin {
  fn identifier(
    &self,
    parser: &mut JavascriptParser,
    ident: &swc_core::ecma::ast::Ident,
    for_name: &str,
  ) -> Option<bool> {
    // Skip CJS handling if not enabled
    if !self.handle_cjs {
      return None;
    }

    let Some(node_option) = parser.compiler_options.node.as_ref() else {
      // When node: false, this plugin is not registered for CJS modules
      return None;
    };
    if for_name == DIRNAME {
      let dirname = match node_option.dirname {
        NodeDirnameOption::Mock => Some(MOCK_DIRNAME.to_string()),
        NodeDirnameOption::WarnMock => {
          parser.add_warning(Diagnostic::warn(
            "NODE_DIRNAME".to_string(),
            format!("\"{}\" is used and has been mocked. Remove it from your code, or set `{}` to disable this warning.", yellow(&DIRNAME), cyan(&"node.__dirname")),
          ));
          Some(MOCK_DIRNAME.to_string())
        }
        NodeDirnameOption::NodeModule => {
          // `ExternalModuleDependency` extends `CachedConstDependency` in webpack.
          // We need to create two separate dependencies in Rspack.
          Self::add_cjs_node_module_dependency(
            parser,
            ident.span,
            DIRNAME,
            NodeMetaProperty::Dirname,
          );
          return Some(true);
        }
        NodeDirnameOption::EvalOnly => {
          // For CJS output, preserve __dirname (let Node.js runtime handle it)
          if !parser.compiler_options.output.module {
            return None;
          }
          Self::add_cjs_node_module_dependency(
            parser,
            ident.span,
            DIRNAME,
            NodeMetaProperty::Dirname,
          );
          return Some(true);
        }
        NodeDirnameOption::True => Some(
          parser
            .resource_data
            .path()?
            .parent()?
            .as_std_path()
            .relative(&parser.compiler_options.context)
            .to_string_lossy()
            .to_string(),
        ),
        NodeDirnameOption::False => None,
      };
      if let Some(dirname) = dirname {
        parser.add_presentational_dependency(Box::new(ConstDependency::new(
          ident.span.into(),
          rspack_util::json_stringify_str(&dirname).into(),
        )));
        return Some(true);
      }
    } else if for_name == FILENAME {
      let filename = match node_option.filename {
        NodeFilenameOption::Mock => Some(MOCK_FILENAME.to_string()),
        NodeFilenameOption::WarnMock => {
          parser.add_warning(Diagnostic::warn(
            "NODE_FILENAME".to_string(),
            format!("\"{}\" is used and has been mocked. Remove it from your code, or set `{}` to disable this warning.", yellow(&FILENAME), cyan(&"node.__filename")),
          ));
          Some(MOCK_FILENAME.to_string())
        }
        NodeFilenameOption::NodeModule => {
          // `ExternalModuleDependency` extends `CachedConstDependency` in webpack.
          // We need to create two separate dependencies in Rspack.
          Self::add_cjs_node_module_dependency(
            parser,
            ident.span,
            FILENAME,
            NodeMetaProperty::Filename,
          );
          return Some(true);
        }
        NodeFilenameOption::EvalOnly => {
          // For CJS output, preserve __filename (let Node.js runtime handle it)
          if !parser.compiler_options.output.module {
            return None;
          }
          Self::add_cjs_node_module_dependency(
            parser,
            ident.span,
            FILENAME,
            NodeMetaProperty::Filename,
          );
          return Some(true);
        }
        NodeFilenameOption::True => Some(
          parser
            .resource_data
            .path()?
            .as_std_path()
            .relative(&parser.compiler_options.context)
            .to_string_lossy()
            .to_string(),
        ),
        NodeFilenameOption::False => None,
      };
      if let Some(filename) = filename {
        parser.add_presentational_dependency(Box::new(ConstDependency::new(
          ident.span.into(),
          rspack_util::json_stringify_str(&filename).into(),
        )));
        return Some(true);
      }
    } else if for_name == GLOBAL
      && matches!(
        node_option.global,
        NodeGlobalOption::True | NodeGlobalOption::Warn
      )
    {
      parser.add_presentational_dependency(Box::new(RuntimeRequirementsDependency::new(
        ident.span.into(),
        RuntimeGlobals::GLOBAL,
      )));
      return Some(true);
    }
    None
  }

  fn rename(&self, parser: &mut JavascriptParser, expr: &Expr, for_name: &str) -> Option<bool> {
    // Skip CJS handling if not enabled
    if !self.handle_cjs {
      return None;
    }

    let node_option = parser.compiler_options.node.as_ref()?;
    if for_name == GLOBAL
      && matches!(
        node_option.global,
        NodeGlobalOption::True | NodeGlobalOption::Warn
      )
    {
      parser.add_presentational_dependency(Box::new(RuntimeRequirementsDependency::new(
        expr.span().into(),
        RuntimeGlobals::GLOBAL,
      )));
      return Some(false);
    }
    None
  }

  fn r#typeof(
    &self,
    parser: &mut JavascriptParser,
    unary_expr: &swc_core::ecma::ast::UnaryExpr,
    for_name: &str,
  ) -> Option<bool> {
    use crate::visitors::expr_name;

    match for_name {
      FILENAME => {
        // Skip CJS __filename if not handling CJS
        if !self.handle_cjs {
          return None;
        }
        // Skip if node: false or node.filename is disabled
        if parser.compiler_options.node.is_none()
          || parser
            .compiler_options
            .node
            .as_ref()
            .is_some_and(|node_option| matches!(node_option.filename, NodeFilenameOption::False))
        {
          return None;
        }
      }
      expr_name::IMPORT_META_FILENAME => {
        // Skip ESM import.meta.filename if not handling ESM
        if !self.handle_esm {
          return None;
        }
        // Skip if importMeta is disabled
        if matches!(
          parser.javascript_options.import_meta,
          Some(ImportMeta::Disabled)
        ) {
          return None;
        }
        // Skip if node: false or node.filename is disabled
        if parser.compiler_options.node.is_none()
          || parser
            .compiler_options
            .node
            .as_ref()
            .is_some_and(|node_option| matches!(node_option.filename, NodeFilenameOption::False))
        {
          return None;
        }
      }
      DIRNAME => {
        // Skip CJS __dirname if not handling CJS
        if !self.handle_cjs {
          return None;
        }
        // Skip if node: false or node.dirname is disabled
        if parser.compiler_options.node.is_none()
          || parser
            .compiler_options
            .node
            .as_ref()
            .is_some_and(|node_option| matches!(node_option.dirname, NodeDirnameOption::False))
        {
          return None;
        }
      }
      expr_name::IMPORT_META_DIRNAME => {
        // Skip ESM import.meta.dirname if not handling ESM
        if !self.handle_esm {
          return None;
        }
        // Skip if importMeta is disabled
        if matches!(
          parser.javascript_options.import_meta,
          Some(ImportMeta::Disabled)
        ) {
          return None;
        }
        // Skip if node: false or node.dirname is disabled
        if parser.compiler_options.node.is_none()
          || parser
            .compiler_options
            .node
            .as_ref()
            .is_some_and(|node_option| matches!(node_option.dirname, NodeDirnameOption::False))
        {
          return None;
        }
      }
      _ => return None,
    }

    parser.add_presentational_dependency(Box::new(ConstDependency::new(
      unary_expr.span().into(),
      "'string'".into(),
    )));
    Some(true)
  }

  fn evaluate_typeof<'a>(
    &self,
    parser: &mut JavascriptParser,
    expr: &'a swc_core::ecma::ast::UnaryExpr,
    for_name: &str,
  ) -> Option<eval::BasicEvaluatedExpression<'a>> {
    use crate::visitors::expr_name;

    match for_name {
      expr_name::IMPORT_META_FILENAME => {
        // Skip processing if importMeta is disabled
        if matches!(
          parser.javascript_options.import_meta,
          Some(ImportMeta::Disabled)
        ) {
          return None;
        }
        // Skip processing if node: false or node.filename is disabled
        if parser.compiler_options.node.is_none()
          || parser
            .compiler_options
            .node
            .as_ref()
            .is_some_and(|node_option| matches!(node_option.filename, NodeFilenameOption::False))
        {
          return None;
        }
        Some(eval::evaluate_to_string(
          "string".to_string(),
          expr.span.real_lo(),
          expr.span.real_hi(),
        ))
      }
      expr_name::IMPORT_META_DIRNAME => {
        // Skip processing if importMeta is disabled
        if matches!(
          parser.javascript_options.import_meta,
          Some(ImportMeta::Disabled)
        ) {
          return None;
        }
        // Skip processing if node: false or node.dirname is disabled
        if parser.compiler_options.node.is_none()
          || parser
            .compiler_options
            .node
            .as_ref()
            .is_some_and(|node_option| matches!(node_option.dirname, NodeDirnameOption::False))
        {
          return None;
        }
        Some(eval::evaluate_to_string(
          "string".to_string(),
          expr.span.real_lo(),
          expr.span.real_hi(),
        ))
      }
      _ => None,
    }
  }

  fn evaluate_identifier(
    &self,
    parser: &mut JavascriptParser,
    for_name: &str,
    start: u32,
    end: u32,
  ) -> Option<crate::utils::eval::BasicEvaluatedExpression<'static>> {
    use crate::visitors::expr_name;

    if for_name == DIRNAME {
      // Skip CJS handling if not enabled
      if !self.handle_cjs {
        return None;
      }
      // Skip if node: false or node.dirname is disabled
      if parser.compiler_options.node.is_none()
        || parser
          .compiler_options
          .node
          .as_ref()
          .is_some_and(|node_option| matches!(node_option.dirname, NodeDirnameOption::False))
      {
        return None;
      }
      Some(eval::evaluate_to_string(
        get_context(parser.resource_data).as_str().to_string(),
        start,
        end,
      ))
    } else if for_name == FILENAME {
      // Skip CJS handling if not enabled
      if !self.handle_cjs {
        return None;
      }
      // Skip if node: false or node.filename is disabled
      if parser.compiler_options.node.is_none()
        || parser
          .compiler_options
          .node
          .as_ref()
          .is_some_and(|node_option| matches!(node_option.filename, NodeFilenameOption::False))
      {
        return None;
      }
      let resource = parse_resource(parser.resource_data.path()?.as_str())?;
      Some(eval::evaluate_to_string(
        resource.path.to_string(),
        start,
        end,
      ))
    } else if for_name == expr_name::IMPORT_META_FILENAME
      || for_name == expr_name::IMPORT_META_DIRNAME
    {
      // Skip ESM handling if not enabled
      if !self.handle_esm {
        return None;
      }
      // Skip processing if importMeta is disabled
      if matches!(
        parser.javascript_options.import_meta,
        Some(ImportMeta::Disabled)
      ) {
        return None;
      }
      let property = if for_name == expr_name::IMPORT_META_FILENAME {
        NodeMetaProperty::Filename
      } else {
        NodeMetaProperty::Dirname
      };
      let value = Self::get_import_meta_eval_value(parser, property)?;
      Some(eval::evaluate_to_string(value, start, end))
    } else {
      None
    }
  }

  fn member(
    &self,
    parser: &mut JavascriptParser,
    member_expr: &swc_core::ecma::ast::MemberExpr,
    for_name: &str,
  ) -> Option<bool> {
    use crate::visitors::expr_name;

    // Skip ESM handling if not enabled
    if !self.handle_esm {
      return None;
    }

    let property = match for_name {
      expr_name::IMPORT_META_FILENAME => NodeMetaProperty::Filename,
      expr_name::IMPORT_META_DIRNAME => NodeMetaProperty::Dirname,
      _ => return None,
    };

    // Skip processing if importMeta is disabled
    if matches!(
      parser.javascript_options.import_meta,
      Some(ImportMeta::Disabled)
    ) {
      return None;
    }

    let replacement = Self::get_import_meta_member_replacement(parser, property)?;
    parser.add_presentational_dependency(Box::new(ConstDependency::new(
      member_expr.span().into(),
      replacement.into(),
    )));
    Some(true)
  }

  fn import_meta_property_in_destructuring(
    &self,
    parser: &mut JavascriptParser,
    property: &DestructuringAssignmentProperty,
  ) -> Option<String> {
    // Skip ESM handling if not enabled
    if !self.handle_esm {
      return None;
    }

    // Skip processing if importMeta is disabled
    if matches!(
      parser.javascript_options.import_meta,
      Some(ImportMeta::Disabled)
    ) {
      return None;
    }

    let meta_property = match property.id.as_str() {
      "filename" => NodeMetaProperty::Filename,
      "dirname" => NodeMetaProperty::Dirname,
      _ => return None,
    };

    let value = Self::get_import_meta_destructuring_value(parser, meta_property)?;
    Some(format!("{}: {value}", property.id))
  }
}