0
# Module Resolution
1
2
Vite's module resolution system provides advanced module resolution with support for aliases, conditions, custom resolvers, and various asset types. It handles ES modules, CommonJS, and provides comprehensive path resolution capabilities.
3
4
## Capabilities
5
6
### ID Resolver
7
8
Create a module ID resolver with customizable resolution logic.
9
10
```typescript { .api }
11
/**
12
* Create module ID resolver
13
* @param config - Resolved Vite configuration
14
* @returns Promise resolving to IdResolver instance
15
*/
16
function createIdResolver(config: ResolvedConfig): Promise<IdResolver>;
17
18
interface IdResolver {
19
/** Resolve module ID */
20
resolve(id: string, importer?: string, options?: ResolveOptions): Promise<string | undefined>;
21
}
22
```
23
24
### Resolve Options
25
26
Configure module resolution behavior including aliases, conditions, and extensions.
27
28
```typescript { .api }
29
interface ResolveOptions {
30
/** Path aliases */
31
alias?: AliasOptions;
32
/** Dedupe dependencies */
33
dedupe?: string[];
34
/** Resolve conditions */
35
conditions?: string[];
36
/** Main fields to check */
37
mainFields?: string[];
38
/** File extensions to try */
39
extensions?: string[];
40
/** External packages */
41
external?: string[];
42
/** Preserve symlinks */
43
preserveSymlinks?: boolean;
44
/** Prefer relative imports */
45
preferRelative?: boolean;
46
}
47
48
interface InternalResolveOptions extends ResolveOptions {
49
/** Root directory */
50
root?: string;
51
/** Is production build */
52
isProduction?: boolean;
53
/** Is require call */
54
isRequire?: boolean;
55
/** SSR target */
56
ssrTarget?: SSRTarget;
57
/** Package cache */
58
packageCache?: Map<string, any>;
59
/** ID only resolution */
60
idOnly?: boolean;
61
/** Scan flag */
62
scan?: boolean;
63
}
64
```
65
66
**Usage Examples:**
67
68
```typescript
69
import { defineConfig } from "vite";
70
71
export default defineConfig({
72
resolve: {
73
alias: {
74
'@': './src',
75
'@components': './src/components',
76
'@utils': './src/utils'
77
},
78
extensions: ['.js', '.ts', '.jsx', '.tsx', '.json'],
79
conditions: ['import', 'module', 'browser', 'default'],
80
mainFields: ['browser', 'module', 'main'],
81
dedupe: ['react', 'react-dom']
82
}
83
});
84
```
85
86
### Alias Configuration
87
88
Configure path aliases for cleaner imports and module resolution.
89
90
```typescript { .api }
91
type AliasOptions = readonly Alias[] | Record<string, string>;
92
93
interface Alias {
94
/** Find pattern (string or regex) */
95
find: string | RegExp;
96
/** Replacement path */
97
replacement: string;
98
/** Custom resolver function */
99
customResolver?: ResolverFunction | ResolverObject;
100
}
101
102
/**
103
* Custom alias resolver function
104
*/
105
type ResolverFunction = (
106
id: string,
107
importer?: string,
108
options?: ResolveOptions
109
) => string | undefined | Promise<string | undefined>;
110
111
interface ResolverObject {
112
buildStart?: () => void;
113
resolveId: ResolverFunction;
114
}
115
116
/**
117
* Function to map aliases
118
*/
119
type MapToFunction<T> = T | ((id: string) => T);
120
```
121
122
### File Pattern Matching
123
124
Utilities for filtering and matching file patterns.
125
126
```typescript { .api }
127
/**
128
* Create file filter function
129
* @param include - Patterns to include
130
* @param exclude - Patterns to exclude
131
* @param options - Filter options
132
* @returns Filter function
133
*/
134
function createFilter(
135
include?: FilterPattern,
136
exclude?: FilterPattern,
137
options?: {
138
resolve?: string | false | null;
139
}
140
): (id: string | unknown) => boolean;
141
142
type FilterPattern = string | RegExp | (string | RegExp)[];
143
```
144
145
### Path Utilities
146
147
Utility functions for path normalization and manipulation.
148
149
```typescript { .api }
150
/**
151
* Normalize file path separators
152
* @param id - Path to normalize
153
* @returns Normalized path
154
*/
155
function normalizePath(id: string): string;
156
157
/**
158
* Check if request is for CSS
159
* @param request - Request path or URL
160
* @returns Whether request is for CSS file
161
*/
162
function isCSSRequest(request: string): boolean;
163
```
164
165
### Asset Detection
166
167
Functions to detect and handle different asset types.
168
169
```typescript { .api }
170
/**
171
* Check if file is an asset
172
* @param file - File path
173
* @param assetsInclude - Asset inclusion patterns
174
* @returns Whether file is treated as asset
175
*/
176
function isAsset(file: string, assetsInclude?: (file: string) => boolean): boolean;
177
178
/**
179
* Check if request is for static asset
180
* @param url - Request URL
181
* @returns Whether URL is for static asset
182
*/
183
function isStaticAsset(url: string): boolean;
184
```
185
186
### Workspace Root Detection
187
188
Find the workspace root directory for monorepo setups.
189
190
```typescript { .api }
191
/**
192
* Search for workspace root directory
193
* @param current - Current directory to start search
194
* @param root - Project root directory
195
* @returns Workspace root path
196
*/
197
function searchForWorkspaceRoot(current: string, root?: string): string;
198
```
199
200
## Resolution Types
201
202
```typescript { .api }
203
interface ResolvedUrl {
204
/** Resolved URL */
205
url: string;
206
/** Original URL */
207
pathname: string;
208
/** Query string */
209
search: string;
210
/** URL hash */
211
hash: string;
212
}
213
214
/**
215
* Resolution result
216
*/
217
interface ResolvedResult {
218
/** Resolved ID */
219
id: string;
220
/** Whether module is external */
221
external?: boolean;
222
/** Module metadata */
223
meta?: Record<string, any>;
224
}
225
226
/**
227
* Module resolution function type
228
*/
229
type ResolveFn = (
230
id: string,
231
importer?: string,
232
options?: {
233
custom?: any;
234
isEntry?: boolean;
235
skipSelf?: boolean;
236
}
237
) => Promise<string | undefined>;
238
```
239
240
## Asset Type Detection
241
242
Built-in asset type detection for various file formats.
243
244
```typescript { .api }
245
/**
246
* Default asset extensions supported by Vite
247
*/
248
const KNOWN_ASSET_TYPES = [
249
// images
250
'apng', 'bmp', 'png', 'jpg', 'jpeg', 'jfif', 'pjpeg', 'pjp', 'gif', 'svg', 'ico', 'webp', 'avif', 'cur', 'jxl',
251
// media
252
'mp4', 'webm', 'ogg', 'mp3', 'wav', 'flac', 'aac', 'opus', 'mov', 'm4a', 'vtt',
253
// fonts
254
'woff', 'woff2', 'eot', 'ttf', 'otf',
255
// other
256
'webmanifest', 'pdf', 'txt'
257
];
258
259
/**
260
* Check if file extension is a known asset type
261
* @param ext - File extension
262
* @returns Whether extension is a known asset type
263
*/
264
function isKnownAssetType(ext: string): boolean;
265
```
266
267
## Advanced Resolution Patterns
268
269
### Conditional Exports
270
271
Support for package.json conditional exports.
272
273
```typescript { .api }
274
/**
275
* Default conditions for different targets
276
*/
277
const DEFAULT_CLIENT_CONDITIONS = ['import', 'module', 'browser', 'default'];
278
const DEFAULT_SERVER_CONDITIONS = ['import', 'module', 'node', 'default'];
279
const DEFAULT_EXTERNAL_CONDITIONS = ['import', 'module', 'node', 'default'];
280
281
/**
282
* Default main fields for different targets
283
*/
284
const DEFAULT_CLIENT_MAIN_FIELDS = ['browser', 'module', 'jsnext:main', 'jsnext'];
285
const DEFAULT_SERVER_MAIN_FIELDS = ['module', 'jsnext:main', 'jsnext', 'main'];
286
```
287
288
### External Dependencies
289
290
Handle external dependencies that should not be bundled.
291
292
```typescript { .api }
293
/**
294
* Check if module should be externalized
295
* @param id - Module ID
296
* @param external - External configuration
297
* @param isProduction - Whether in production build
298
* @returns Whether module is external
299
*/
300
function isExternal(
301
id: string,
302
external: string[] | ((id: string) => boolean),
303
isProduction: boolean
304
): boolean;
305
```