0
# Code Optimization
1
2
Core code optimization functionality including constant folding, dead code elimination, and expression evaluation at compile time for improved bundle performance.
3
4
## Capabilities
5
6
### Constant Folding Plugin
7
8
Performs compile-time evaluation of expressions and dead code elimination to reduce bundle size.
9
10
```javascript { .api }
11
/**
12
* Creates a Babel plugin that performs constant folding and dead code elimination
13
* @param context - Babel plugin context with types and traverse utilities
14
* @returns Babel plugin object with visitor pattern
15
*/
16
function constantFoldingPlugin(context: {
17
types: Types,
18
traverse: Traverse
19
}): PluginObj<State>;
20
21
interface State {
22
stripped: boolean; // Tracks whether any code was removed
23
}
24
```
25
26
**Usage Examples:**
27
28
```javascript
29
const babel = require("@babel/core");
30
const { constantFoldingPlugin } = require("metro-transform-plugins");
31
32
// Basic constant folding
33
const code = `
34
const result = 2 + 3 * 4;
35
if (true) {
36
console.log("always executed");
37
} else {
38
console.log("never executed");
39
}
40
`;
41
42
const transformed = babel.transformSync(code, {
43
plugins: [
44
constantFoldingPlugin({ types: babel.types, traverse: babel.traverse })
45
]
46
});
47
48
// Result will have expressions evaluated and dead code removed:
49
// const result = 14;
50
// console.log("always executed");
51
```
52
53
### Expression Evaluation
54
55
The plugin evaluates various types of expressions at compile time:
56
57
- **Binary expressions**: `2 + 3` becomes `5`
58
- **Unary expressions**: `!false` becomes `true`
59
- **Logical expressions**: `true || anything` becomes `true`
60
- **Conditional expressions**: `true ? 'yes' : 'no'` becomes `'yes'`
61
62
```javascript { .api }
63
/**
64
* Internal evaluation function (not directly exported)
65
* Safely evaluates expressions with confidence checking
66
*/
67
interface EvaluationResult {
68
confident: boolean; // Whether evaluation was successful
69
value: any; // The evaluated value
70
}
71
```
72
73
### Dead Code Elimination
74
75
Removes unreachable code and unused declarations:
76
77
```javascript
78
// Before transformation
79
if (false) {
80
expensiveOperation(); // This will be removed
81
}
82
83
function unusedFunction() { // This will be removed if never referenced
84
return 42;
85
}
86
87
// After transformation - dead code is completely eliminated
88
```
89
90
### Conditional Statement Optimization
91
92
Optimizes conditional statements based on constant test expressions:
93
94
```javascript { .api }
95
// Handles these node types:
96
// - IfStatement: if/else conditional statements
97
// - ConditionalExpression: ternary operators (condition ? true : false)
98
// - LogicalExpression: logical operators (&&, ||, ??)
99
```
100
101
**Logical Expression Optimization:**
102
103
```javascript
104
// Before
105
const value = condition || 'default';
106
const checked = flag && someValue;
107
const nullish = input ?? 'fallback';
108
109
// After (when condition/flag/input are constant)
110
const value = 'default'; // if condition was false
111
const checked = someValue; // if flag was true
112
const nullish = 'fallback'; // if input was null/undefined
113
```
114
115
### Function Declaration Removal
116
117
Removes unused function declarations that are never referenced:
118
119
```javascript { .api }
120
/**
121
* Removes function declarations that have no references
122
* Checks binding.referenced to determine usage
123
*/
124
// FunctionDeclaration visitor handles:
125
// - Named function declarations
126
// - Function expressions assigned to variables
127
// - Arrow functions assigned to variables
128
```
129
130
### Safety Checks
131
132
The plugin includes safety mechanisms to avoid breaking code:
133
134
- **Assignment expressions**: Marked as unsafe to prevent side effect removal
135
- **Function calls**: Marked as unsafe to preserve potential side effects
136
- **Optional call expressions**: `foo?.()` marked as unsafe to prevent incorrect optimization
137
- **Void expressions**: Only optimized when argument is a literal (e.g., `void 0`)
138
139
```javascript { .api }
140
/**
141
* Safety checking prevents optimization of expressions that may have side effects
142
*/
143
interface SafetyState {
144
safe: boolean; // Tracks whether expression is safe to optimize
145
}
146
```
147
148
### Iterative Processing
149
150
The plugin performs multiple passes until no more optimizations are possible:
151
152
```javascript
153
// The plugin will re-traverse the AST if any changes were made
154
// This ensures cascading optimizations are applied:
155
// const a = 1 + 2; // First pass: a = 3
156
// const b = a * 4; // Second pass: b = 12
157
```