0
# Resolution Context
1
2
The ResolutionContext provides all the configuration settings, file system operations, and helper functions needed for module resolution. It serves as the central configuration object that controls how the resolver behaves.
3
4
## Capabilities
5
6
### ResolutionContext Interface
7
8
The main configuration interface for the resolver.
9
10
```typescript { .api }
11
interface ResolutionContext {
12
/** Whether to allow Haste module resolution */
13
readonly allowHaste: boolean;
14
15
/** File extensions considered as assets */
16
readonly assetExts: ReadonlyArray<string>;
17
18
/** File extensions considered as source files */
19
readonly sourceExts: ReadonlyArray<string>;
20
21
/** Options passed to custom resolvers */
22
readonly customResolverOptions: CustomResolverOptions;
23
24
/** Whether to disable hierarchical node_modules lookup */
25
readonly disableHierarchicalLookup: boolean;
26
27
/** Function to check if a file exists (deprecated, prefer fileSystemLookup) */
28
readonly doesFileExist: DoesFileExist;
29
30
/** Additional node_modules paths for resolution */
31
readonly extraNodeModules?: { [key: string]: string };
32
33
/** Function to perform file system lookups */
34
readonly fileSystemLookup: FileSystemLookup;
35
36
/** Function to parse package.json files */
37
readonly getPackage: (packageJsonPath: string) => PackageJson | null;
38
39
/** Function to get package info for a module path (deprecated) */
40
readonly getPackageForModule: (absoluteModulePath: string) => PackageForModule | null;
41
42
/** Dependency descriptor for diagnostic purposes */
43
readonly dependency?: any;
44
45
/** Whether the dependency was declared with ESM import syntax */
46
readonly isESMImport?: boolean;
47
48
/** Ordered list of package.json fields to check for main entry point */
49
readonly mainFields: ReadonlyArray<string>;
50
51
/** Path of the module requesting the resolution */
52
readonly originModulePath: string;
53
54
/** Global node_modules paths to search */
55
readonly nodeModulesPaths: ReadonlyArray<string>;
56
57
/** Whether to prefer .native files over platform-specific files */
58
readonly preferNativePlatform: boolean;
59
60
/** Function to resolve asset files */
61
readonly resolveAsset: ResolveAsset;
62
63
/** Function to redirect module paths */
64
readonly redirectModulePath: (modulePath: string) => string | false;
65
66
/** Function to resolve Haste modules */
67
readonly resolveHasteModule: (name: string) => string | undefined;
68
69
/** Function to resolve Haste packages */
70
readonly resolveHastePackage: (name: string) => string | undefined;
71
72
/** Custom resolver function */
73
readonly resolveRequest?: CustomResolver;
74
75
/** Condition names for package exports resolution */
76
unstable_conditionNames: ReadonlyArray<string>;
77
78
/** Platform-specific condition names */
79
unstable_conditionsByPlatform: Readonly<{ [platform: string]: ReadonlyArray<string> }>;
80
81
/** Whether to enable package.json exports field support */
82
unstable_enablePackageExports: boolean;
83
84
/** Function to log warnings */
85
unstable_logWarning: (message: string) => void;
86
}
87
```
88
89
### Helper Function Types
90
91
Functions that integrate with the file system and package resolution.
92
93
```typescript { .api }
94
/** Check if a file exists at the given path */
95
type DoesFileExist = (filePath: string) => boolean;
96
97
/** Perform file system lookup with type information */
98
type FileSystemLookup = (
99
absoluteOrProjectRelativePath: string
100
) => { exists: false } | { exists: true; type: 'f' | 'd'; realPath: string };
101
102
/** Resolve asset files in a directory */
103
type ResolveAsset = (
104
dirPath: string,
105
assetName: string,
106
extension: string
107
) => ReadonlyArray<string> | undefined;
108
```
109
110
### Custom Resolver Options
111
112
Configuration options for custom resolvers.
113
114
```typescript { .api }
115
type CustomResolverOptions = Readonly<{
116
[option: string]: unknown;
117
}>;
118
```
119
120
### Creating Default Context
121
122
Helper function to create a ResolutionContext with default settings.
123
124
```typescript { .api }
125
/**
126
* Helper function to create a ResolutionContext with default values
127
* @param context - Partial context with custom overrides
128
* @param dependency - Dependency information for diagnostics
129
* @returns Complete ResolutionContext
130
*/
131
function createDefaultContext(
132
context: Partial<ResolutionContext>,
133
dependency: any
134
): ResolutionContext;
135
```
136
137
**Usage Examples:**
138
139
```javascript
140
const { createDefaultContext } = require("metro-resolver");
141
142
// Create context with common settings
143
const context = createDefaultContext({
144
allowHaste: false,
145
assetExts: ['png', 'jpg', 'gif', 'webp'],
146
sourceExts: ['js', 'jsx', 'ts', 'tsx', 'json'],
147
mainFields: ['browser', 'main', 'module'],
148
originModulePath: '/app/src/index.js',
149
nodeModulesPaths: ['/app/node_modules'],
150
fileSystemLookup: (path) => {
151
const fs = require('fs');
152
try {
153
const stats = fs.lstatSync(path);
154
return {
155
exists: true,
156
type: stats.isDirectory() ? 'd' : 'f',
157
realPath: fs.realpathSync(path)
158
};
159
} catch {
160
return { exists: false };
161
}
162
},
163
getPackage: (packagePath) => {
164
try {
165
return require(packagePath);
166
} catch {
167
return null;
168
}
169
},
170
resolveAsset: (dirPath, name, ext) => {
171
// Custom asset resolution logic
172
return [`${dirPath}/${name}${ext}`];
173
},
174
unstable_enablePackageExports: true,
175
unstable_logWarning: console.warn
176
}, null);
177
```
178
179
### File System Integration
180
181
The context provides abstracted file system operations for flexibility.
182
183
```typescript { .api }
184
interface FileSystemLookupResult {
185
exists: boolean;
186
type?: 'f' | 'd';
187
realPath?: string;
188
}
189
```
190
191
**Usage Example:**
192
193
```javascript
194
const context = {
195
// ... other config
196
fileSystemLookup: (path) => {
197
const fs = require('fs');
198
try {
199
const stats = fs.lstatSync(path);
200
return {
201
exists: true,
202
type: stats.isDirectory() ? 'd' : 'f',
203
realPath: fs.realpathSync(path)
204
};
205
} catch (error) {
206
return { exists: false };
207
}
208
}
209
};
210
```
211
212
### Package Integration
213
214
Functions for working with package.json files and package structure.
215
216
```typescript { .api }
217
interface PackageJson {
218
readonly name?: string;
219
readonly main?: string;
220
readonly exports?: string | ExportMap;
221
readonly imports?: ExportMap;
222
readonly browser?: string | { [key: string]: string | false };
223
readonly module?: string;
224
}
225
226
interface PackageInfo {
227
readonly packageJson: PackageJson;
228
readonly rootPath: string;
229
}
230
231
interface PackageForModule extends PackageInfo {
232
readonly packageRelativePath: string;
233
}
234
```
235
236
### Main Fields Configuration
237
238
Controls the order of package.json fields checked for entry points.
239
240
**Common Configurations:**
241
242
```javascript
243
// Browser-first (for web bundling)
244
mainFields: ['browser', 'module', 'main']
245
246
// Node.js-first
247
mainFields: ['main', 'module']
248
249
// React Native
250
mainFields: ['react-native', 'browser', 'main']
251
```
252
253
### Platform-Specific Configuration
254
255
Settings for handling platform-specific resolution.
256
257
```typescript { .api }
258
interface PlatformConfiguration {
259
/** Whether to prefer .native files over platform-specific files */
260
preferNativePlatform: boolean;
261
262
/** Condition names for exports resolution */
263
unstable_conditionNames: ReadonlyArray<string>;
264
265
/** Platform-specific condition names */
266
unstable_conditionsByPlatform: Readonly<{ [platform: string]: ReadonlyArray<string> }>;
267
}
268
```
269
270
**Usage Example:**
271
272
```javascript
273
const context = {
274
// ... other config
275
preferNativePlatform: true,
276
unstable_conditionNames: ['import', 'require'],
277
unstable_conditionsByPlatform: {
278
ios: ['react-native', 'ios', 'native', 'import'],
279
android: ['react-native', 'android', 'native', 'import'],
280
web: ['browser', 'import']
281
}
282
};
283
```
284
285
### Haste Configuration
286
287
Settings for Haste module system integration.
288
289
```typescript { .api }
290
interface HasteConfiguration {
291
/** Whether to allow Haste module resolution */
292
allowHaste: boolean;
293
294
/** Function to resolve Haste modules by name */
295
resolveHasteModule: (name: string) => string | undefined;
296
297
/** Function to resolve Haste packages by name */
298
resolveHastePackage: (name: string) => string | undefined;
299
}
300
```
301
302
### Asset Configuration
303
304
Settings for asset file resolution.
305
306
```typescript { .api }
307
interface AssetConfiguration {
308
/** File extensions considered as assets */
309
assetExts: ReadonlyArray<string>;
310
311
/** Function to resolve asset files */
312
resolveAsset: ResolveAsset;
313
}
314
```
315
316
**Common Asset Extensions:**
317
318
```javascript
319
assetExts: [
320
'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg',
321
'mp4', 'webm', 'wav', 'mp3', 'm4a', 'aac',
322
'otf', 'ttf', 'woff', 'woff2'
323
]
324
```