0
# import-lazy
1
2
import-lazy provides lazy loading functionality for Node.js modules using JavaScript Proxy objects. It defers the actual import/require operation until the module is first accessed, helping reduce initial load time and memory consumption in applications where certain modules may not always be used.
3
4
## Package Information
5
6
- **Package Name**: import-lazy
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript definitions)
9
- **Installation**: `npm install import-lazy`
10
11
## Core Imports
12
13
```javascript
14
const importLazy = require('import-lazy');
15
```
16
17
TypeScript:
18
19
```typescript
20
import importLazy = require('import-lazy');
21
```
22
23
## Basic Usage
24
25
```javascript
26
const importLazy = require('import-lazy');
27
28
// Create a lazy import function bound to require
29
const lazyRequire = importLazy(require);
30
31
// Import modules lazily - they won't be loaded until first access
32
const _ = lazyRequire('lodash');
33
const fs = lazyRequire('fs');
34
35
// Module is loaded only when first accessed
36
_.isNumber(42); // lodash is loaded and cached now
37
_.isString('hello'); // subsequent calls use cached module
38
39
// Works with local modules too
40
const utils = lazyRequire('./utils');
41
console.log(utils.formatDate(new Date()));
42
```
43
44
## Capabilities
45
46
### Lazy Import Function Factory
47
48
Creates a lazy import function that uses the provided import function to load modules on demand.
49
50
```javascript { .api }
51
/**
52
* Creates a lazy import function that defers module loading until first access
53
* @param {function} importFn - Function to use for importing modules (typically require)
54
* @returns {function} A function that creates lazy proxies for modules
55
*/
56
function importLazy(importFn) {
57
return function(moduleId) {
58
// Returns a Proxy that loads the module on first access
59
return new Proxy(function () {}, {
60
get: (target, property) => { /* loads module and returns property */ },
61
apply: (target, thisArgument, argumentsList) => { /* loads module and applies as function */ },
62
construct: (target, argumentsList) => { /* loads module and constructs instance */ }
63
});
64
};
65
}
66
```
67
68
**Parameters:**
69
- `importFn` (function): Import function to use for loading modules, typically `require`
70
- Signature: `(moduleId: string) => any`
71
- Description: Function that performs the actual module import/require
72
73
**Returns:**
74
- Function that takes a `moduleId` (string) and returns a Proxy object
75
76
**Usage Examples:**
77
78
```javascript
79
// Standard usage with require
80
const importLazy = require('import-lazy');
81
const lazyRequire = importLazy(require);
82
const lodash = lazyRequire('lodash');
83
84
// Custom import function
85
const customImport = (moduleId) => {
86
console.log(`Loading ${moduleId}`);
87
return require(moduleId);
88
};
89
const lazyCustom = importLazy(customImport);
90
const moment = lazyCustom('moment');
91
```
92
93
### Lazy Module Proxy
94
95
The proxy object returned by the lazy import function supports all standard JavaScript operations.
96
97
```javascript { .api }
98
/**
99
* Proxy object that intercepts module access and loads the target module on demand
100
* Supports property access, function calls, and constructor invocations
101
*/
102
interface LazyModuleProxy {
103
// Supports any property access - loads module on first access
104
[key: string]: any;
105
// Supports function calls - loads module if it's a function
106
(...args: any[]): any;
107
// Supports constructor calls - loads module if it's a class
108
new (...args: any[]): any;
109
}
110
```
111
112
**Supported Operations:**
113
114
1. **Property Access**: `lazyModule.someProperty`
115
2. **Method Calls**: `lazyModule.someMethod(args)`
116
3. **Function Calls**: `lazyModule(args)` (if module exports a function)
117
4. **Constructor Calls**: `new LazyModule(args)` (if module exports a class)
118
119
**Usage Examples:**
120
121
```javascript
122
const importLazy = require('import-lazy');
123
const lazyRequire = importLazy(require);
124
125
// Property access
126
const chalk = lazyRequire('chalk');
127
console.log(chalk.red('Error message')); // chalk loaded on first access
128
129
// Function calls (module exports a function)
130
const validator = lazyRequire('validator');
131
const isEmail = validator.isEmail('test@example.com');
132
133
// Constructor calls (module exports a class)
134
const EventEmitter = lazyRequire('events');
135
const emitter = new EventEmitter();
136
137
// Mixed usage (object with functions and properties)
138
const path = lazyRequire('path');
139
console.log(path.sep); // property access
140
const joined = path.join('/usr', 'local'); // method call
141
```
142
143
## Important Behaviors
144
145
### Lazy Loading
146
Modules are only loaded when first accessed through the proxy. This helps reduce initial application startup time and memory usage.
147
148
### Caching
149
Once a module is loaded, it's cached for all subsequent accesses. The actual module object is used directly after the first load.
150
151
### Destructuring Limitation
152
**Warning**: Destructuring assignment will cause immediate module loading, negating the lazy behavior:
153
154
```javascript
155
// This will load the module immediately
156
const {isNumber, isString} = lazyRequire('lodash');
157
158
// Equivalent to:
159
const {isNumber, isString} = require('lodash');
160
```
161
162
### Proxy Implementation
163
The lazy loading is implemented using JavaScript Proxy objects with handlers for:
164
- `get`: Property access and method retrieval
165
- `apply`: Function calls when the module itself is a function
166
- `construct`: Constructor calls when the module is a class
167
168
## TypeScript Support
169
170
import-lazy includes TypeScript definitions for type safety:
171
172
```typescript { .api }
173
/**
174
* Import a module lazily using a Proxy that defers loading until first access
175
* @template T - Type of the module being imported
176
* @param importFn - Function to use for importing modules (typically require)
177
* @returns A function that creates lazy proxies for modules of type T
178
*/
179
declare function importLazy<T = unknown>(
180
importFn: (moduleId: string) => T
181
): (moduleId: string) => T;
182
183
export = importLazy;
184
```
185
186
**Usage in TypeScript:**
187
188
```typescript
189
import importLazy = require('import-lazy');
190
191
// Type-safe usage
192
const lazyRequire = importLazy(require);
193
const lodash = lazyRequire('lodash'); // Type: unknown by default
194
195
// With custom typing
196
interface LodashModule {
197
isNumber(value: any): value is number;
198
isString(value: any): value is string;
199
}
200
201
const typedLazyRequire = importLazy<LodashModule>(require);
202
const typedLodash = typedLazyRequire('lodash'); // Type: LodashModule
203
```
204
205
## Browser/Environment Support
206
207
- **Node.js Version**: Requires Node.js >=8
208
- **Engine Requirements**: Modern JavaScript features (Proxy, Reflect)
209
- **Browser Support**: Not designed for browser use (uses Node.js require patterns)
210
211
## Common Use Cases
212
213
1. **CLI Tools**: Reduce startup time by lazy loading command-specific modules
214
2. **Plugin Systems**: Load plugins only when needed
215
3. **Large Applications**: Defer loading of heavy modules until required
216
4. **Conditional Module Loading**: Load modules based on runtime conditions without immediate overhead