0
# Default Configuration
1
2
Generate sensible default configuration for Metro bundler with all required options and platform-specific settings.
3
4
## Capabilities
5
6
### Get Default Configuration
7
8
Returns a complete Metro configuration with sensible defaults for all components.
9
10
```javascript { .api }
11
/**
12
* Gets default Metro configuration with sensible defaults
13
* @param rootPath - Project root directory (optional, defaults to auto-detected)
14
* @returns Promise resolving to complete default Metro configuration
15
*/
16
function getDefaultConfig(rootPath?: string): Promise<ConfigT>;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
import { getDefaultConfig } from "metro-config";
23
24
// Get default config with auto-detected project root
25
const defaultConfig = await getDefaultConfig();
26
27
// Get default config with specific project root
28
const defaultConfig = await getDefaultConfig('/path/to/project');
29
30
// Use as base for custom configuration
31
const customConfig = {
32
...await getDefaultConfig(),
33
server: {
34
...defaultConfig.server,
35
port: 3000 // Override port
36
}
37
};
38
```
39
40
### Get Default Values (Synchronous)
41
42
Access default configuration values synchronously (useful for testing or advanced scenarios).
43
44
```javascript { .api }
45
/**
46
* Gets default configuration values synchronously
47
* @param rootPath - Project root directory (optional)
48
* @returns Complete default Metro configuration object
49
*/
50
getDefaultConfig.getDefaultValues(rootPath?: string): ConfigT;
51
```
52
53
**Usage Examples:**
54
55
```javascript
56
import { getDefaultConfig } from "metro-config";
57
58
// Get default values synchronously
59
const defaults = getDefaultConfig.getDefaultValues();
60
61
// With specific root path
62
const defaults = getDefaultConfig.getDefaultValues('/path/to/project');
63
```
64
65
## Default Configuration Structure
66
67
### Resolver Configuration
68
69
Module resolution settings for finding and processing files:
70
71
```javascript
72
{
73
resolver: {
74
// Supported asset file extensions
75
assetExts: ['bmp', 'gif', 'jpg', 'jpeg', 'png', 'psd', 'svg', 'webp', 'm4v', 'mov', 'mp4', 'mpeg', 'mpg', 'webm', 'aac', 'aiff', 'caf', 'm4a', 'mp3', 'wav', 'html', 'pdf', 'yaml', 'yml', 'otf', 'ttf', 'zip'],
76
77
// Supported asset resolutions (for @2x, @3x assets)
78
assetResolutions: ['1x', '1.5x', '2x', '3x', '4x'],
79
80
// Supported platforms
81
platforms: ['ios', 'android', 'native', 'web'],
82
83
// Source file extensions
84
sourceExts: ['js', 'jsx', 'json', 'ts', 'tsx'],
85
86
// Files/directories to exclude
87
blockList: [/(^|\/|\\)node_modules($|\/|\\)/],
88
89
// Module resolution settings
90
disableHierarchicalLookup: false,
91
enableGlobalPackages: false,
92
resolverMainFields: ['browser', 'main'],
93
useWatchman: true,
94
95
// Package exports support
96
unstable_enablePackageExports: true,
97
unstable_conditionNames: [],
98
unstable_conditionsByPlatform: {
99
web: ['browser']
100
}
101
}
102
}
103
```
104
105
### Serializer Configuration
106
107
Bundle serialization and output settings:
108
109
```javascript
110
{
111
serializer: {
112
// Module ID generation
113
createModuleIdFactory: () => (path) => hash(path),
114
115
// Bundle execution statements
116
getRunModuleStatement: (moduleId, globalPrefix) => `__r(${JSON.stringify(moduleId)});`,
117
118
// Polyfills and initialization
119
getPolyfills: () => [],
120
getModulesRunBeforeMainModule: () => [],
121
polyfillModuleNames: [],
122
123
// Module filtering
124
processModuleFilter: (module) => true,
125
isThirdPartyModule: (module) => /(?:^|[/\\])node_modules[/\\]/.test(module.path),
126
127
// Custom serialization
128
customSerializer: null,
129
experimentalSerializerHook: () => {}
130
}
131
}
132
```
133
134
### Server Configuration
135
136
Development server settings:
137
138
```javascript
139
{
140
server: {
141
// Server configuration
142
port: 8081,
143
forwardClientLogs: true,
144
useGlobalHotkey: true,
145
verifyConnections: false,
146
147
// URL rewriting
148
rewriteRequestUrl: (url) => url,
149
150
// Middleware enhancement (deprecated)
151
enhanceMiddleware: (middleware, server) => middleware,
152
153
// Server root (experimental)
154
unstable_serverRoot: null
155
}
156
}
157
```
158
159
### Transformer Configuration
160
161
Code transformation settings:
162
163
```javascript
164
{
165
transformer: {
166
// Babel transformer
167
babelTransformerPath: 'metro-babel-transformer',
168
enableBabelRCLookup: true,
169
enableBabelRuntime: true,
170
171
// Asset handling
172
assetRegistryPath: 'missing-asset-registry-path',
173
assetPlugins: [],
174
175
// Transform options
176
getTransformOptions: async () => ({
177
transform: {
178
experimentalImportSupport: false,
179
inlineRequires: false,
180
unstable_disableES6Transforms: false
181
},
182
preloadedModules: false,
183
ramGroups: []
184
}),
185
186
// Minification
187
minifierPath: 'metro-minify-terser',
188
minifierConfig: {
189
mangle: { toplevel: false },
190
output: {
191
ascii_only: true,
192
quote_style: 3,
193
wrap_iife: true
194
},
195
compress: { reduce_funcs: false }
196
},
197
198
// Performance settings
199
optimizationSizeLimit: 150 * 1024, // 150 KiB
200
unstable_workerThreads: false,
201
202
// Module handling
203
dynamicDepsInPackages: 'throwAtRuntime',
204
allowOptionalDependencies: false,
205
206
// Experimental features
207
unstable_allowRequireContext: false,
208
unstable_disableModuleWrapping: false,
209
unstable_compactOutput: false
210
}
211
}
212
```
213
214
### Watcher Configuration
215
216
File watching and health check settings:
217
218
```javascript
219
{
220
watcher: {
221
// Additional file extensions to watch
222
additionalExts: ['cjs', 'mjs'],
223
224
// Health check system
225
healthCheck: {
226
enabled: false,
227
filePrefix: '.metro-health-check',
228
interval: 30000, // 30 seconds
229
timeout: 5000 // 5 seconds
230
},
231
232
// Auto-save cache
233
unstable_autoSaveCache: {
234
enabled: true,
235
debounceMs: 5000
236
},
237
238
// Performance optimizations
239
unstable_lazySha1: true,
240
unstable_workerThreads: false,
241
242
// Watchman integration
243
watchman: {
244
deferStates: ['hg.update']
245
}
246
}
247
}
248
```
249
250
### Core Configuration
251
252
Core Metro settings:
253
254
```javascript
255
{
256
// Project settings
257
projectRoot: '/path/to/project',
258
watchFolders: [],
259
260
// Caching
261
cacheVersion: '1.0',
262
cacheStores: [
263
new FileStore({
264
root: path.join(os.tmpdir(), 'metro-cache')
265
})
266
],
267
268
// Worker processes
269
maxWorkers: require('os').cpus().length,
270
stickyWorkers: true,
271
272
// Transformer worker
273
transformerPath: 'metro-transform-worker',
274
275
// Development
276
resetCache: false,
277
reporter: new TerminalReporter(new Terminal(process.stdout)),
278
279
// Performance logging
280
unstable_perfLoggerFactory: () => ({
281
point: () => {},
282
annotate: () => {},
283
subSpan: () => this
284
})
285
}
286
```
287
288
## Platform-Specific Defaults
289
290
### Web Platform
291
292
When building for web, additional defaults are applied:
293
294
```javascript
295
{
296
resolver: {
297
unstable_conditionsByPlatform: {
298
web: ['browser']
299
}
300
}
301
}
302
```
303
304
### React Native
305
306
Default configuration is optimized for React Native development:
307
308
- Asset extensions include native image and video formats
309
- Platforms include 'ios', 'android', 'native'
310
- Resolver configured for React Native module resolution
311
- Transform options optimized for mobile performance
312
313
## Customizing Defaults
314
315
### Override Specific Options
316
317
```javascript
318
import { getDefaultConfig } from "metro-config";
319
320
const config = {
321
...await getDefaultConfig(),
322
server: {
323
...defaultConfig.server,
324
port: 3000 // Custom port
325
},
326
resolver: {
327
...defaultConfig.resolver,
328
sourceExts: [...defaultConfig.resolver.sourceExts, 'svg'] // Add SVG support
329
}
330
};
331
```
332
333
### Environment-Specific Defaults
334
335
```javascript
336
import { getDefaultConfig } from "metro-config";
337
338
async function createConfig() {
339
const baseConfig = await getDefaultConfig();
340
341
if (process.env.NODE_ENV === 'production') {
342
return {
343
...baseConfig,
344
transformer: {
345
...baseConfig.transformer,
346
minifierConfig: {
347
...baseConfig.transformer.minifierConfig,
348
compress: {
349
...baseConfig.transformer.minifierConfig.compress,
350
drop_console: true // Remove console.log in production
351
}
352
}
353
}
354
};
355
}
356
357
return baseConfig;
358
}
359
```
360
361
### Project Root Detection
362
363
If no `rootPath` is provided, Metro Config automatically detects the project root:
364
365
1. Looks for the nearest `package.json` file
366
2. Defaults to two levels up from `node_modules/metro/`
367
3. Falls back to current working directory
368
369
```javascript
370
// These are equivalent if run from project root
371
const config1 = await getDefaultConfig();
372
const config2 = await getDefaultConfig(process.cwd());
373
const config3 = await getDefaultConfig('./');
374
```