0
# Module Alias
1
2
Module Alias is a Node.js library that enables creating aliases for directories and registering custom module paths. It eliminates the need for complex relative path traversals in require statements by allowing developers to define custom aliases in their package.json configuration or programmatically through its API.
3
4
## Package Information
5
6
- **Package Name**: module-alias
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install module-alias`
10
11
## Core Imports
12
13
**Main API (programmatic usage):**
14
15
```javascript
16
const moduleAlias = require('module-alias');
17
```
18
19
**Automatic initialization entry point:**
20
21
```javascript
22
require('module-alias/register');
23
```
24
25
The `module-alias/register` entry point automatically calls the main `init()` function to load configuration from package.json. This is the recommended approach for most applications as it requires minimal setup.
26
27
## Basic Usage
28
29
Module Alias can be used in two ways: automatic initialization via package.json configuration or programmatic setup.
30
31
**Automatic Setup (package.json configuration):**
32
33
Add aliases to your package.json:
34
35
```json
36
{
37
"_moduleAliases": {
38
"@root": ".",
39
"@src": "src/",
40
"@deep": "src/some/very/deep/directory"
41
},
42
"_moduleDirectories": ["custom_modules"]
43
}
44
```
45
46
Then initialize at the start of your main file:
47
48
```javascript
49
require('module-alias/register');
50
51
// Now you can use aliases
52
const myModule = require('@src/my-module');
53
const deepModule = require('@deep/module');
54
const customModule = require('my-custom-module'); // from custom_modules directory
55
```
56
57
**Programmatic Setup:**
58
59
```javascript
60
const moduleAlias = require('module-alias');
61
62
// Initialize from package.json
63
moduleAlias();
64
65
// Or register aliases manually
66
moduleAlias.addAlias('@root', __dirname);
67
moduleAlias.addAlias('@src', __dirname + '/src');
68
69
// Register custom module directories
70
moduleAlias.addPath(__dirname + '/custom_modules');
71
72
// Now use the aliases
73
const myModule = require('@src/my-module');
74
```
75
76
## Architecture
77
78
Module Alias is built around Node.js's internal module resolution system and consists of several key components:
79
80
- **Module Resolution Hooks**: Intercepts Node.js's `Module._resolveFilename` method to check registered aliases before normal module resolution
81
- **Path Resolution System**: Modifies `Module._nodeModulePaths` to include custom directories in the module search path
82
- **Alias Registry**: Maintains sorted arrays and objects for efficient alias matching during module resolution
83
- **Configuration Parser**: Reads package.json configuration and converts relative paths to absolute paths
84
- **Custom Handler System**: Supports function-based aliases for dynamic path resolution based on calling context
85
86
The library works by patching Node.js's internal module system at runtime, allowing it to intercept `require()` calls and apply custom resolution logic before falling back to the default behavior.
87
88
## Capabilities
89
90
### Initialization
91
92
Initialize module aliases from package.json configuration.
93
94
```javascript { .api }
95
/**
96
* Initialize aliases and custom module paths from package.json
97
* @param {string|object} [options] - Base path string or options object
98
* @param {string} [options.base] - Base directory path for resolving aliases
99
*/
100
function init(options);
101
```
102
103
**Parameters:**
104
- `options` (optional): Can be either:
105
- **String**: Direct path to directory containing package.json (shorthand for `{base: string}`)
106
- **Object**: Configuration object with properties:
107
- `base` (string): Base directory path for resolving relative alias paths
108
109
**Behavior:**
110
- If no options provided, searches for package.json in current working directory or two levels up from node_modules
111
- Reads `_moduleAliases` and `_moduleDirectories` from package.json
112
- Converts relative alias paths to absolute paths using the base directory
113
114
### Alias Management
115
116
Register and manage module path aliases.
117
118
```javascript { .api }
119
/**
120
* Register a single alias mapping
121
* @param {string} alias - The alias name (e.g., '@root')
122
* @param {string|function} target - Target path or custom handler function
123
*/
124
function addAlias(alias, target);
125
126
/**
127
* Register multiple alias mappings
128
* @param {object} aliases - Object with alias->target mappings
129
*/
130
function addAliases(aliases);
131
```
132
133
**Custom Handler Function:**
134
135
For dynamic alias resolution, provide a function as the target:
136
137
```javascript { .api }
138
/**
139
* Custom handler function for dynamic alias resolution
140
* @param {string} fromPath - Full path of the file from which require was called
141
* @param {string} request - The path that was passed into require
142
* @param {string} alias - The alias that was passed to addAlias
143
* @returns {string} - Resolved path
144
*/
145
type AliasHandler = (fromPath: string, request: string, alias: string) => string;
146
```
147
148
Usage example:
149
150
```javascript
151
moduleAlias.addAlias('@src', (fromPath, request, alias) => {
152
// Custom logic based on the calling file
153
if (fromPath.startsWith(__dirname + '/tests')) {
154
return __dirname + '/test-src';
155
}
156
return __dirname + '/src';
157
});
158
```
159
160
### Custom Module Paths
161
162
Register custom directories that act like node_modules.
163
164
```javascript { .api }
165
/**
166
* Register custom module directory (like node_modules)
167
* @param {string} path - Path to custom module directory
168
*/
169
function addPath(path);
170
```
171
172
### Path Matching
173
174
Check if a path matches a given alias pattern.
175
176
```javascript { .api }
177
/**
178
* Check if a path matches a given alias pattern
179
* @param {string} path - Path to test
180
* @param {string} alias - Alias pattern to match against
181
* @returns {boolean} - True if path matches the alias
182
*/
183
function isPathMatchesAlias(path, alias);
184
```
185
186
### Reset
187
188
Reset all registered aliases and custom module paths (primarily for testing).
189
190
```javascript { .api }
191
/**
192
* Reset all registered aliases and custom module paths
193
* Note: This function is undocumented and intended for testing purposes only
194
*/
195
function reset();
196
```
197
198
## Package.json Configuration
199
200
### Module Aliases
201
202
Define aliases in your package.json for automatic registration:
203
204
```json { .api }
205
{
206
"_moduleAliases": {
207
"@root": ".",
208
"@src": "src/",
209
"@components": "src/components/",
210
"@utils": "src/utils/",
211
"custom-name": "path/to/module"
212
}
213
}
214
```
215
216
- Keys are the alias names (can start with @ or be any string)
217
- Values are relative paths from the package.json location
218
- Absolute paths (starting with /) are used as-is
219
220
### Custom Module Directories
221
222
Define custom module directories that work like node_modules:
223
224
```json { .api }
225
{
226
"_moduleDirectories": [
227
"custom_modules",
228
"src/shared-modules"
229
]
230
}
231
```
232
233
- Array of directory names/paths
234
- These directories will be searched for modules like node_modules
235
- "node_modules" should not be included (it's automatically handled)
236
237
## Error Handling
238
239
The library throws specific errors in certain conditions:
240
241
**Custom Handler Error**: Thrown when a custom handler function returns a falsy or non-string value
242
```javascript
243
moduleAlias.addAlias('@src', () => {
244
// Returns undefined - will throw error
245
});
246
247
require('@src'); // Throws: "[module-alias] Expecting custom handler function to return path."
248
```
249
250
**Package.json Not Found Error**: Thrown when package.json cannot be located during initialization
251
```javascript
252
moduleAlias({ base: '/nonexistent/path' });
253
// Throws: "Unable to find package.json in any of:\n[/nonexistent/path]"
254
```
255
256
## Compatibility
257
258
**Compatible with:**
259
- All Node.js versions
260
- CommonJS and ES6 imports (via transpilation)
261
- require.resolve()
262
263
**Not compatible with:**
264
- Front-end JavaScript frameworks (use Webpack's resolve.alias instead)
265
- Jest testing framework (use Jest's moduleNameMapper instead)
266
- NCC compiler
267
- Browser environments
268
269
## Implementation Details
270
271
Module Alias works by intercepting Node.js's internal module resolution:
272
273
- **Alias Resolution**: Modifies `Module._resolveFilename` to check for registered aliases before normal resolution
274
- **Custom Paths**: Modifies `Module._nodeModulePaths` to include custom directories in the module search path
275
- **Performance**: Aliases are sorted for efficient matching during resolution
276
277
The library maintains internal data structures:
278
- `moduleAliases`: Object storing alias-to-path mappings
279
- `moduleAliasNames`: Sorted array of alias names for efficient matching
280
- `modulePaths`: Array of custom module directory paths