0
# Module Importing
1
2
Cross-environment dynamic module importing that works consistently in both CommonJS and ESM contexts, providing a unified interface for dynamic imports with proper interop handling.
3
4
## Capabilities
5
6
### Dynamic Module Import
7
8
Import modules dynamically with automatic interop handling for cross-environment compatibility.
9
10
```typescript { .api }
11
/**
12
* Import modules dynamically with cross-environment compatibility
13
* @param path - Module path to import (can be package name or file path)
14
* @returns Promise resolving to the imported module with proper interop
15
*/
16
function importModule<T = any>(path: string): Promise<T>;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { importModule } from "local-pkg";
23
24
// Import a package by name
25
const express = await importModule("express");
26
const app = express();
27
28
// Import specific utilities from a package
29
const { join } = await importModule("node:path");
30
const fullPath = join("/home", "user", "file.txt");
31
32
// Import from a resolved path
33
const modulePath = "/path/to/node_modules/lodash/index.js";
34
const lodash = await importModule(modulePath);
35
const result = lodash.map([1, 2, 3], x => x * 2);
36
37
// Generic type support
38
interface MyModule {
39
doSomething: (x: string) => number;
40
}
41
const myModule = await importModule<MyModule>("./my-module.js");
42
const result = myModule.doSomething("hello");
43
```
44
45
## Cross-Environment Compatibility
46
47
The `importModule` function handles the differences between CommonJS and ESM module systems automatically:
48
49
### ESM Environment
50
```typescript
51
// In ESM context
52
const chalk = await importModule("chalk");
53
// Equivalent to: const chalk = await import("chalk");
54
```
55
56
### CommonJS Environment
57
```typescript
58
// In CJS context - works the same way
59
const chalk = await importModule("chalk");
60
// Handles interop automatically, equivalent to dynamic import with proper default handling
61
```
62
63
### Interop Handling
64
65
The function automatically handles default export interop, ensuring consistent behavior regardless of how the target module was exported:
66
67
```typescript
68
// These all work correctly regardless of module format
69
const express = await importModule("express"); // Default export
70
const { readFile } = await importModule("node:fs/promises"); // Named exports
71
const entire = await importModule("some-package"); // Mixed exports
72
```
73
74
## Error Handling
75
76
Import failures are handled through standard Promise rejection:
77
78
```typescript
79
import { importModule } from "local-pkg";
80
81
try {
82
const module = await importModule("nonexistent-package");
83
} catch (error) {
84
console.error("Failed to import module:", error.message);
85
}
86
87
// Or with promise chaining
88
importModule("some-package")
89
.then(module => {
90
// Use the imported module
91
console.log(module);
92
})
93
.catch(error => {
94
console.error("Import failed:", error);
95
});
96
```
97
98
## Type Safety
99
100
The function supports TypeScript generics for type-safe imports when you know the shape of the imported module:
101
102
```typescript
103
// Define the expected module interface
104
interface UtilityModule {
105
helper: (input: string) => string;
106
constant: number;
107
}
108
109
// Import with type safety
110
const utils = await importModule<UtilityModule>("./utils");
111
utils.helper("test"); // TypeScript knows this exists and its signature
112
console.log(utils.constant); // TypeScript knows this is a number
113
```