Skip to main content

stylex_transform/transform/fold/
fold_module.rs

1use swc_core::{
2  common::comments::Comments,
3  ecma::{ast::Module, visit::FoldWith},
4};
5
6use crate::{StyleXTransform, shared::utils::common::fill_top_level_expressions};
7use stylex_enums::core::TransformationCycle;
8
9impl<C> StyleXTransform<C>
10where
11  C: Comments,
12{
13  pub(crate) fn fold_module_impl(&mut self, module: Module) -> Module {
14    if cfg!(debug_assertions) || !self.state.options.use_real_file_for_source {
15      self.state.set_seen_module_source_code(&module, None);
16    }
17
18    let mut module = module.fold_children_with(self);
19
20    if !self.state.import_paths.is_empty() {
21      self.state.cycle = TransformationCycle::StateFilling;
22      module = module.fold_children_with(self);
23
24      fill_top_level_expressions(&module, &mut self.state);
25
26      self.state.cycle = TransformationCycle::TransformEnter;
27      module = module.fold_children_with(self);
28
29      self.state.cycle = TransformationCycle::TransformExit;
30      module = module.fold_children_with(self);
31
32      if self.state.options.runtime_injection.is_some() {
33        self.state.cycle = TransformationCycle::InjectStyles;
34        module = module.fold_children_with(self);
35      }
36
37      self.state.cycle = TransformationCycle::PreCleaning;
38      module = module.fold_children_with(self);
39
40      self.state.cycle = TransformationCycle::Cleaning;
41
42      // NOTE: Reversing the module body to clean the module items in the correct order,
43      // so removing unused variable declarations will more efficient
44      // After cleaning the module items, the module body will be reversed back to its original order
45      module.body.reverse();
46
47      module = module.fold_children_with(self);
48
49      module.body.reverse();
50
51      module
52    } else {
53      self.state.cycle = TransformationCycle::Skip;
54      module
55    }
56  }
57}