0
# Configuration Loading
1
2
Load Metro configuration from files with automatic discovery, multiple format support, and CLI argument integration.
3
4
## Capabilities
5
6
### Load Configuration
7
8
Loads Metro configuration from the file system with automatic discovery and validation.
9
10
```javascript { .api }
11
/**
12
* Loads Metro configuration from various sources with automatic discovery
13
* @param argvInput - CLI arguments and configuration options (optional)
14
* @param defaultConfigOverrides - Base config overrides (optional)
15
* @returns Promise resolving to complete Metro configuration
16
*/
17
function loadConfig(
18
argvInput?: YargArguments,
19
defaultConfigOverrides?: InputConfigT
20
): Promise<ConfigT>;
21
```
22
23
**Usage Examples:**
24
25
```javascript
26
import { loadConfig } from "metro-config";
27
28
// Auto-discover config file in current directory
29
const config = await loadConfig();
30
31
// Load from specific config file
32
const config = await loadConfig({
33
config: './metro.config.js'
34
});
35
36
// Override with CLI arguments
37
const config = await loadConfig({
38
config: './metro.config.js',
39
port: 3000,
40
projectRoot: './src',
41
resetCache: true
42
});
43
44
// With workspace configuration
45
const config = await loadConfig({
46
cwd: './packages/mobile',
47
watchFolders: ['./packages/shared']
48
});
49
50
// With default config overrides
51
const config = await loadConfig(
52
{ config: './metro.config.js' },
53
{
54
resolver: { sourceExts: ['js', 'jsx', 'ts', 'tsx'] },
55
server: { port: 3000 }
56
}
57
);
58
```
59
60
### Resolve Configuration
61
62
Finds and loads configuration files from the file system with search hierarchy.
63
64
```javascript { .api }
65
/**
66
* Resolves configuration file path and loads the config
67
* @param filePath - Explicit path to config file (optional)
68
* @param cwd - Current working directory for search (optional)
69
* @returns Promise resolving to config resolution result
70
*/
71
function resolveConfig(filePath?: string, cwd?: string): Promise<ResolveConfigResult>;
72
73
interface ResolveConfigResult {
74
/** Absolute path to the resolved config file */
75
filepath: string;
76
/** Whether the config is empty (no file found) */
77
isEmpty: boolean;
78
/** The loaded configuration object or function */
79
config: (ConfigT => Promise<ConfigT>) | (ConfigT => ConfigT) | InputConfigT;
80
}
81
82
type ResolveConfigResult = $ReadOnly<{
83
filepath: string,
84
isEmpty: boolean,
85
config: (ConfigT => Promise<ConfigT>) | (ConfigT => ConfigT) | InputConfigT,
86
}>;
87
```
88
89
**Usage Examples:**
90
91
```javascript
92
import { resolveConfig } from "metro-config";
93
94
// Auto-discover config file
95
const result = await resolveConfig();
96
if (!result.isEmpty) {
97
console.log(`Found config at: ${result.filepath}`);
98
}
99
100
// Search from specific directory
101
const result = await resolveConfig(undefined, './packages/mobile');
102
103
// Load specific file
104
const result = await resolveConfig('./custom-metro.config.js');
105
```
106
107
### Load Configuration File
108
109
Directly loads a configuration file from a specific absolute path.
110
111
```javascript { .api }
112
/**
113
* Loads a configuration file from an absolute path
114
* @param absolutePath - Absolute path to the config file
115
* @returns Promise resolving to config resolution result
116
*/
117
function loadConfigFile(absolutePath: string): Promise<ResolveConfigResult>;
118
```
119
120
**Usage Examples:**
121
122
```javascript
123
import { loadConfigFile } from "metro-config";
124
125
// Load specific config file
126
const result = await loadConfigFile('/absolute/path/to/metro.config.js');
127
128
// Check if config was loaded successfully
129
if (!result.isEmpty) {
130
console.log(`Loaded config from: ${result.filepath}`);
131
132
// Handle function vs object config
133
if (typeof result.config === 'function') {
134
console.log('Config is a function that will receive default config');
135
} else {
136
console.log('Config is a static object');
137
}
138
}
139
```
140
141
## Configuration File Discovery
142
143
Metro Config searches for configuration files in the following order:
144
145
### Supported File Names
146
147
1. **JavaScript/JSON files:**
148
- `metro.config.js`
149
- `metro.config.cjs`
150
- `metro.config.mjs`
151
- `metro.config.json`
152
153
2. **TypeScript files:**
154
- `metro.config.ts`
155
- `metro.config.cts`
156
- `metro.config.mts`
157
158
3. **Config directory:**
159
- `.config/metro.js`
160
- `.config/metro.cjs`
161
- `.config/metro.mjs`
162
- `.config/metro.json`
163
- `.config/metro.ts`
164
- `.config/metro.cts`
165
- `.config/metro.mts`
166
167
4. **Package.json:**
168
- `package.json` (using "metro" property)
169
170
### Search Hierarchy
171
172
1. Explicit file path (if provided)
173
2. Current working directory
174
3. Parent directories (walking up the file system)
175
4. User home directory
176
177
### Configuration Formats
178
179
**JavaScript Export (recommended):**
180
181
```javascript
182
// metro.config.js
183
module.exports = {
184
resolver: {
185
sourceExts: ['js', 'jsx', 'ts', 'tsx']
186
},
187
server: {
188
port: 8081
189
}
190
};
191
```
192
193
**JavaScript Function:**
194
195
```javascript
196
// metro.config.js
197
module.exports = async (defaultConfig) => {
198
return {
199
...defaultConfig,
200
resolver: {
201
...defaultConfig.resolver,
202
sourceExts: [...defaultConfig.resolver.sourceExts, 'svg']
203
}
204
};
205
};
206
```
207
208
**TypeScript:**
209
210
```typescript
211
// metro.config.ts
212
import type { ConfigT } from 'metro-config';
213
214
const config: ConfigT = {
215
resolver: {
216
sourceExts: ['js', 'jsx', 'ts', 'tsx']
217
}
218
};
219
220
export default config;
221
```
222
223
**Package.json:**
224
225
```json
226
{
227
"metro": {
228
"resolver": {
229
"sourceExts": ["js", "jsx", "ts", "tsx"]
230
}
231
}
232
}
233
```
234
235
## CLI Arguments Integration
236
237
### Supported CLI Arguments
238
239
```javascript { .api }
240
type YargArguments = $ReadOnly<{
241
/** Path to configuration file */
242
config?: string,
243
/** Current working directory */
244
cwd?: string,
245
/** Development server port */
246
port?: string | number,
247
/** Development server host */
248
host?: string,
249
/** Project root directory */
250
projectRoot?: string,
251
/** Additional watch folders */
252
watchFolders?: Array<string>,
253
/** Asset file extensions */
254
assetExts?: Array<string>,
255
/** Source file extensions */
256
sourceExts?: Array<string>,
257
/** Supported platforms */
258
platforms?: Array<string>,
259
/** Maximum worker processes */
260
'max-workers'?: string | number,
261
maxWorkers?: string | number,
262
/** Transformer module path */
263
transformer?: string,
264
/** Reset Metro cache */
265
'reset-cache'?: boolean,
266
resetCache?: boolean,
267
/** Verbose logging */
268
verbose?: boolean,
269
}>;
270
```
271
272
**Usage Examples:**
273
274
```javascript
275
// Override configuration with CLI arguments
276
const config = await loadConfig({
277
config: './metro.config.js',
278
port: 3000,
279
resetCache: true,
280
maxWorkers: 4,
281
watchFolders: ['./packages/shared', './packages/common'],
282
sourceExts: ['js', 'jsx', 'ts', 'tsx', 'json']
283
});
284
```
285
286
## Error Handling
287
288
Configuration loading includes comprehensive error handling:
289
290
```javascript
291
import { loadConfig } from "metro-config";
292
293
try {
294
const config = await loadConfig({
295
config: './invalid-config.js'
296
});
297
} catch (error) {
298
if (error.code === 'MODULE_NOT_FOUND') {
299
console.error('Configuration file not found');
300
} else if (error.name === 'ValidationError') {
301
console.error('Invalid configuration:', error.message);
302
} else {
303
console.error('Configuration loading failed:', error);
304
}
305
}
306
```
307
308
## Configuration Validation
309
310
All loaded configurations are validated using Jest's validation system:
311
312
- **Schema validation**: Ensures all configuration properties are valid
313
- **Type checking**: Validates property types and structure
314
- **Warning system**: Provides helpful warnings for deprecated options
315
- **Error reporting**: Clear error messages for invalid configurations