0
# Metro Config
1
2
Metro Config is the configuration parser and resolver for Metro bundler. It provides utilities for loading, merging, and validating Metro configuration files from various sources, with comprehensive type definitions and sensible defaults for all Metro components.
3
4
## Package Information
5
6
- **Package Name**: metro-config
7
- **Package Type**: npm
8
- **Language**: JavaScript (with Flow types)
9
- **Installation**: `npm install metro-config`
10
11
## Core Imports
12
13
```javascript
14
import { getDefaultConfig, loadConfig, loadConfigFile, mergeConfig, resolveConfig } from "metro-config";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { getDefaultConfig, loadConfig, loadConfigFile, mergeConfig, resolveConfig } = require("metro-config");
21
```
22
23
For type definitions:
24
25
```javascript
26
import type { ConfigT, InputConfigT, YargArguments } from "metro-config";
27
```
28
29
## Basic Usage
30
31
```javascript
32
import { getDefaultConfig, loadConfig, mergeConfig } from "metro-config";
33
34
// Get default Metro configuration
35
const defaultConfig = await getDefaultConfig();
36
37
// Load config from file system (auto-discovery)
38
const userConfig = await loadConfig();
39
40
// Load config from specific path
41
const customConfig = await loadConfig({
42
config: './custom-metro.config.js'
43
});
44
45
// Merge configurations
46
const finalConfig = mergeConfig(defaultConfig, userConfig);
47
48
// Complete workflow example
49
async function setupMetroConfig() {
50
// 1. Get defaults for current project
51
const defaults = await getDefaultConfig();
52
53
// 2. Load user configuration
54
const userConfig = await loadConfig({
55
config: './metro.config.js',
56
port: 3000,
57
resetCache: true
58
});
59
60
// 3. Create platform-specific overrides
61
const webOverrides = {
62
resolver: {
63
unstable_conditionsByPlatform: {
64
web: ['browser', 'import']
65
}
66
}
67
};
68
69
// 4. Merge all configurations
70
const finalConfig = mergeConfig(defaults, userConfig, webOverrides);
71
72
return finalConfig;
73
}
74
```
75
76
## Architecture
77
78
Metro Config is built around several key components:
79
80
- **Configuration Loading**: Automatic discovery and loading of config files from various formats (JS, TS, JSON, YAML)
81
- **Configuration Merging**: Deep merging of configuration objects with validation
82
- **Default Configuration**: Comprehensive defaults for all Metro bundler components
83
- **Type System**: Complete Flow/TypeScript definitions for configuration objects
84
- **Validation**: Schema-based validation using jest-validate
85
- **CLI Integration**: Support for command-line argument overrides
86
87
## Capabilities
88
89
### Configuration Loading
90
91
Load Metro configuration from files, with automatic discovery and support for multiple formats. Handles async configuration functions and CLI argument overrides.
92
93
```javascript { .api }
94
/**
95
* Loads Metro configuration from various sources with automatic discovery
96
* @param argvInput - CLI arguments and configuration options (optional)
97
* @param defaultConfigOverrides - Base config overrides (optional)
98
* @returns Promise resolving to complete Metro configuration
99
*/
100
function loadConfig(
101
argvInput?: YargArguments,
102
defaultConfigOverrides?: InputConfigT
103
): Promise<ConfigT>;
104
105
/**
106
* Resolves configuration file path and loads the config
107
* @param filePath - Explicit path to config file (optional)
108
* @param cwd - Current working directory for search (optional)
109
* @returns Promise resolving to config resolution result
110
*/
111
function resolveConfig(filePath?: string, cwd?: string): Promise<ResolveConfigResult>;
112
113
interface ResolveConfigResult {
114
filepath: string;
115
isEmpty: boolean;
116
config: (ConfigT => Promise<ConfigT>) | (ConfigT => ConfigT) | InputConfigT;
117
}
118
```
119
120
[Configuration Loading](./config-loading.md)
121
122
### Configuration Merging
123
124
Deep merge multiple Metro configurations with validation and type safety.
125
126
```javascript { .api }
127
/**
128
* Deep merges multiple Metro configuration objects
129
* @param defaultConfig - Base configuration object
130
* @param configs - Additional configurations to merge (later configs take precedence)
131
* @returns Complete merged Metro configuration
132
*/
133
function mergeConfig<T: $ReadOnly<InputConfigT>>(
134
defaultConfig: T,
135
...configs: Array<InputConfigT>
136
): T;
137
```
138
139
[Configuration Merging](./config-merging.md)
140
141
### Default Configuration
142
143
Generate sensible default configuration for Metro bundler with all required options.
144
145
```javascript { .api }
146
/**
147
* Gets default Metro configuration with sensible defaults
148
* @param rootPath - Project root directory (optional, defaults to auto-detected)
149
* @returns Promise resolving to complete default Metro configuration
150
*/
151
function getDefaultConfig(rootPath?: string): Promise<ConfigT>;
152
```
153
154
[Default Configuration](./default-config.md)
155
156
## Types
157
158
### Core Configuration Types
159
160
```javascript { .api }
161
// Complete Metro configuration (read-only)
162
type ConfigT = $ReadOnly<{
163
cacheStores: CacheStoresConfigT,
164
cacheVersion: string,
165
maxWorkers: number,
166
projectRoot: string,
167
resolver: $ReadOnly<ResolverConfigT>,
168
serializer: $ReadOnly<SerializerConfigT>,
169
server: $ReadOnly<ServerConfigT>,
170
symbolicator: $ReadOnly<SymbolicatorConfigT>,
171
transformer: $ReadOnly<TransformerConfigT>,
172
watcher: $ReadOnly<WatcherConfigT>,
173
// ... other core config fields
174
}>;
175
176
// User input configuration (partial)
177
type InputConfigT = Partial<$ReadOnly<{
178
// All ConfigT fields as optional/partial
179
}>>;
180
181
// Alias for InputConfigT
182
type MetroConfig = InputConfigT;
183
184
// CLI arguments for configuration
185
type YargArguments = $ReadOnly<{
186
config?: string,
187
cwd?: string,
188
port?: string | number,
189
projectRoot?: string,
190
// ... other CLI options
191
}>;
192
```
193
194
### Component Configuration Types
195
196
```javascript { .api }
197
// Module resolution configuration
198
type ResolverConfigT = {
199
assetExts: $ReadOnlyArray<string>,
200
sourceExts: $ReadOnlyArray<string>,
201
platforms: $ReadOnlyArray<string>,
202
blockList: RegExp | Array<RegExp>,
203
// ... other resolver options
204
};
205
206
// Bundle serialization configuration
207
type SerializerConfigT = {
208
createModuleIdFactory: () => (path: string) => number,
209
getPolyfills: ({platform: ?string}) => $ReadOnlyArray<string>,
210
// ... other serializer options
211
};
212
213
// Code transformation configuration
214
type TransformerConfigT = {
215
assetPlugins: $ReadOnlyArray<string>,
216
asyncRequireModulePath: string,
217
assetRegistryPath: string,
218
babelTransformerPath: string,
219
dynamicDepsInPackages: 'throwAtRuntime' | 'reject',
220
enableBabelRCLookup: boolean,
221
enableBabelRuntime: boolean,
222
getTransformOptions: GetTransformOptions,
223
globalPrefix: string,
224
hermesParser: boolean,
225
minifierConfig: $ReadOnly<{
226
mangle: $ReadOnly<{toplevel: boolean}>,
227
output: $ReadOnly<{
228
ascii_only: boolean,
229
quote_style: number,
230
wrap_iife: boolean,
231
}>,
232
sourceMap: $ReadOnly<{includeSources: boolean}>,
233
toplevel: boolean,
234
compress: $ReadOnly<{reduce_funcs: boolean}>,
235
}>,
236
minifierPath: string,
237
optimizationSizeLimit: number,
238
transformVariants: {+[name: string]: Partial<ExtraTransformOptions>},
239
publicPath: string,
240
allowOptionalDependencies: boolean,
241
unstable_allowRequireContext: boolean,
242
unstable_dependencyMapReservedName: ?string,
243
unstable_disableModuleWrapping: boolean,
244
unstable_disableNormalizePseudoGlobals: boolean,
245
unstable_renameRequire: boolean,
246
unstable_compactOutput: boolean,
247
unstable_memoizeInlineRequires: boolean,
248
unstable_workerThreads: boolean,
249
};
250
```
251
252
### Transform Options Types
253
254
```javascript { .api }
255
type ExtraTransformOptions = $ReadOnly<{
256
preloadedModules?: $ReadOnly<{[path: string]: true}> | false,
257
ramGroups?: $ReadOnlyArray<string>,
258
transform?: $ReadOnly<{
259
experimentalImportSupport?: boolean,
260
inlineRequires?: boolean | $ReadOnly<{blockList: $ReadOnly<{[string]: true}>}>,
261
nonInlinedRequires?: $ReadOnlyArray<string>,
262
unstable_disableES6Transforms?: boolean,
263
unstable_memoizeInlineRequires?: boolean,
264
unstable_nonMemoizedInlineRequires?: $ReadOnlyArray<string>,
265
}>,
266
}>;
267
268
type GetTransformOptions = (
269
entryPoints: $ReadOnlyArray<string>,
270
options: GetTransformOptionsOpts,
271
getDependenciesOf: (string) => Promise<Array<string>>,
272
) => Promise<Partial<ExtraTransformOptions>>;
273
274
type GetTransformOptionsOpts = {
275
dev: boolean,
276
hot: true, // @deprecated Always true
277
platform: ?string,
278
};
279
```