0
# Module Import and Resolution
1
2
Modern asynchronous module importing with TypeScript support and advanced resolution capabilities.
3
4
## Capabilities
5
6
### Asynchronous Import
7
8
Modern promise-based module importing with TypeScript and ESM compatibility.
9
10
```typescript { .api }
11
/**
12
* ESM import a module with additional TypeScript and ESM compatibility
13
* @param id - Module identifier to import
14
* @param opts - Optional resolve options and default export shortcut
15
* @returns Promise resolving to module exports
16
*/
17
import<T = unknown>(
18
id: string,
19
opts?: JitiResolveOptions & { default?: true }
20
): Promise<T>;
21
```
22
23
**Usage Examples:**
24
25
```typescript
26
import { createJiti } from "jiti";
27
28
const jiti = createJiti(import.meta.url);
29
30
// Import TypeScript module
31
const config = await jiti.import("./config.ts");
32
33
// Import with default export shortcut (mod?.default ?? mod)
34
const utils = await jiti.import("./utils.ts", { default: true });
35
36
// Import with specific type
37
interface UserConfig {
38
apiKey: string;
39
timeout: number;
40
}
41
const userConfig = await jiti.import<UserConfig>("./user-config.ts");
42
43
// Import JSON with type safety
44
const packageData = await jiti.import<{ version: string }>("./package.json");
45
46
// Import with resolve options
47
const module = await jiti.import("./module.ts", {
48
conditions: ["import", "node"],
49
try: true // Don't throw on failure
50
});
51
```
52
53
### ESM Resolution
54
55
Advanced module resolution with ESM import conditions and comprehensive options.
56
57
```typescript { .api }
58
/**
59
* Resolve module with ESM import conditions
60
* @param id - Module identifier to resolve
61
* @param opts - Resolution options or parent URL string
62
* @returns Resolved module path or undefined if try option is used
63
*/
64
esmResolve(id: string, opts?: string | JitiResolveOptions): string;
65
esmResolve<T extends JitiResolveOptions = JitiResolveOptions>(
66
id: string,
67
opts?: T
68
): T["try"] extends true ? string | undefined : string;
69
```
70
71
**Usage Examples:**
72
73
```typescript
74
const jiti = createJiti(import.meta.url);
75
76
// Basic resolution
77
const resolved = jiti.esmResolve("./config.ts");
78
console.log(resolved); // file:///path/to/config.ts
79
80
// Resolution with parent URL
81
const resolved = jiti.esmResolve("./utils", "/path/to/parent.js");
82
83
// Resolution with conditions
84
const resolved = jiti.esmResolve("package", {
85
conditions: ["import", "node", "development"]
86
});
87
88
// Safe resolution that doesn't throw
89
const resolved = jiti.esmResolve("./maybe-missing", { try: true });
90
if (resolved) {
91
console.log("Found:", resolved);
92
} else {
93
console.log("Module not found");
94
}
95
96
// Resolution with specific parent URL
97
const resolved = jiti.esmResolve("./relative-module", {
98
parentURL: "file:///specific/parent/dir/"
99
});
100
```
101
102
### Resolution Options
103
104
Comprehensive options for controlling module resolution behavior.
105
106
```typescript { .api }
107
interface JitiResolveOptions {
108
/**
109
* Export conditions to use during resolution
110
* Common values: ["import", "require", "node", "browser", "development", "production"]
111
*/
112
conditions?: string[];
113
114
/**
115
* Parent module URL for resolving relative imports
116
*/
117
parentURL?: string | URL;
118
119
/**
120
* Don't throw on resolution failure, return undefined instead
121
* @default false
122
*/
123
try?: boolean;
124
}
125
```
126
127
### Legacy Synchronous Import (Deprecated)
128
129
Synchronous CommonJS-style import functionality. **Note:** This API is deprecated and may be removed in future versions.
130
131
```typescript { .api }
132
/**
133
* @deprecated Prefer await jiti.import() for better compatibility
134
* Synchronous module import similar to require()
135
*/
136
(id: string): any;
137
138
/**
139
* @deprecated Prefer jiti.esmResolve() for better compatibility
140
* Synchronous module resolution similar to require.resolve()
141
*/
142
resolve: {
143
(id: string, options?: { paths?: string[] }): string;
144
paths(request: string): string[] | null;
145
};
146
```
147
148
**Migration Examples:**
149
150
```typescript
151
// ❌ Deprecated synchronous API
152
const config = jiti("./config.ts");
153
const resolved = jiti.resolve("./config.ts");
154
155
// ✅ Recommended asynchronous API
156
const config = await jiti.import("./config.ts");
157
const resolved = jiti.esmResolve("./config.ts");
158
```
159
160
### Module Types and Interoperability
161
162
jiti provides seamless interoperability between ESM and CommonJS modules with smart default export handling.
163
164
**Default Export Interoperability:**
165
166
```typescript
167
// TypeScript module with default export
168
// config.ts
169
export default { apiKey: "secret", timeout: 5000 };
170
171
// Import patterns
172
const config1 = await jiti.import("./config.ts"); // Full module object
173
const config2 = await jiti.import("./config.ts", { default: true }); // config2 === config1.default || config1
174
175
// Mixed exports module
176
// utils.ts
177
export const helper = () => "help";
178
export default { version: "1.0" };
179
180
const utils = await jiti.import("./utils.ts");
181
// utils = { helper: Function, default: { version: "1.0" } } + Proxy magic for interop
182
console.log(utils.helper()); // "help"
183
console.log(utils.version); // "1.0" (thanks to interopDefault)
184
```
185
186
**File Extension Handling:**
187
188
jiti automatically handles various file extensions:
189
190
```typescript
191
// All of these work automatically
192
await jiti.import("./config.ts"); // TypeScript
193
await jiti.import("./config.mts"); // TypeScript ESM
194
await jiti.import("./config.cts"); // TypeScript CommonJS
195
await jiti.import("./config.tsx"); // TypeScript + JSX
196
await jiti.import("./config.js"); // JavaScript
197
await jiti.import("./config.mjs"); // JavaScript ESM
198
await jiti.import("./config.cjs"); // JavaScript CommonJS
199
await jiti.import("./data.json"); // JSON
200
```
201
202
### Error Handling
203
204
Comprehensive error handling for module import and resolution failures.
205
206
**Import Error Handling:**
207
208
```typescript
209
try {
210
const module = await jiti.import("./non-existent.ts");
211
} catch (error) {
212
console.error("Import failed:", error.message);
213
// Handle missing module
214
}
215
216
// Safe import with try option
217
const module = await jiti.import("./maybe-missing.ts", { try: true });
218
if (!module) {
219
console.log("Module not found, using defaults");
220
}
221
```
222
223
**Resolution Error Handling:**
224
225
```typescript
226
try {
227
const resolved = jiti.esmResolve("./missing-module");
228
} catch (error) {
229
console.error("Resolution failed:", error.message);
230
}
231
232
// Safe resolution
233
const resolved = jiti.esmResolve("./maybe-missing", { try: true });
234
if (!resolved) {
235
console.log("Could not resolve module");
236
}
237
```
238
239
### Advanced Usage Patterns
240
241
**Dynamic Imports with Variables:**
242
243
```typescript
244
const configName = process.env.NODE_ENV || "development";
245
const config = await jiti.import(`./configs/${configName}.ts`);
246
247
// Conditional imports
248
const dbConfig = await jiti.import(
249
process.env.NODE_ENV === "production"
250
? "./db-prod.ts"
251
: "./db-dev.ts"
252
);
253
```
254
255
**Plugin System with Dynamic Loading:**
256
257
```typescript
258
const pluginNames = ["auth", "logging", "cache"];
259
const plugins = await Promise.all(
260
pluginNames.map(name => jiti.import(`./plugins/${name}.ts`))
261
);
262
263
// Type-safe plugin loading
264
interface Plugin {
265
name: string;
266
initialize: () => void;
267
}
268
269
const plugin = await jiti.import<Plugin>("./plugins/custom.ts");
270
plugin.initialize();
271
```
272
273
**Alias Resolution:**
274
275
```typescript
276
// Create jiti with aliases
277
const jiti = createJiti(import.meta.url, {
278
alias: {
279
"@/*": "./src/*",
280
"~/*": "./lib/*",
281
"#components": "./src/components/index.ts"
282
}
283
});
284
285
// Use aliases in imports
286
const utils = await jiti.import("@/utils/helpers.ts");
287
const lib = await jiti.import("~/common.ts");
288
const components = await jiti.import("#components");
289
```