Create aliases of directories and register custom module paths in Node.js
npx @tessl/cli install tessl/npm-module-alias@2.2.0Module 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.
npm install module-aliasMain API (programmatic usage):
const moduleAlias = require('module-alias');Automatic initialization entry point:
require('module-alias/register');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.
Module Alias can be used in two ways: automatic initialization via package.json configuration or programmatic setup.
Automatic Setup (package.json configuration):
Add aliases to your package.json:
{
"_moduleAliases": {
"@root": ".",
"@src": "src/",
"@deep": "src/some/very/deep/directory"
},
"_moduleDirectories": ["custom_modules"]
}Then initialize at the start of your main file:
require('module-alias/register');
// Now you can use aliases
const myModule = require('@src/my-module');
const deepModule = require('@deep/module');
const customModule = require('my-custom-module'); // from custom_modules directoryProgrammatic Setup:
const moduleAlias = require('module-alias');
// Initialize from package.json
moduleAlias();
// Or register aliases manually
moduleAlias.addAlias('@root', __dirname);
moduleAlias.addAlias('@src', __dirname + '/src');
// Register custom module directories
moduleAlias.addPath(__dirname + '/custom_modules');
// Now use the aliases
const myModule = require('@src/my-module');Module Alias is built around Node.js's internal module resolution system and consists of several key components:
Module._resolveFilename method to check registered aliases before normal module resolutionModule._nodeModulePaths to include custom directories in the module search pathThe 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.
Initialize module aliases from package.json configuration.
/**
* Initialize aliases and custom module paths from package.json
* @param {string|object} [options] - Base path string or options object
* @param {string} [options.base] - Base directory path for resolving aliases
*/
function init(options);Parameters:
options (optional): Can be either:
{base: string})base (string): Base directory path for resolving relative alias pathsBehavior:
_moduleAliases and _moduleDirectories from package.jsonRegister and manage module path aliases.
/**
* Register a single alias mapping
* @param {string} alias - The alias name (e.g., '@root')
* @param {string|function} target - Target path or custom handler function
*/
function addAlias(alias, target);
/**
* Register multiple alias mappings
* @param {object} aliases - Object with alias->target mappings
*/
function addAliases(aliases);Custom Handler Function:
For dynamic alias resolution, provide a function as the target:
/**
* Custom handler function for dynamic alias resolution
* @param {string} fromPath - Full path of the file from which require was called
* @param {string} request - The path that was passed into require
* @param {string} alias - The alias that was passed to addAlias
* @returns {string} - Resolved path
*/
type AliasHandler = (fromPath: string, request: string, alias: string) => string;Usage example:
moduleAlias.addAlias('@src', (fromPath, request, alias) => {
// Custom logic based on the calling file
if (fromPath.startsWith(__dirname + '/tests')) {
return __dirname + '/test-src';
}
return __dirname + '/src';
});Register custom directories that act like node_modules.
/**
* Register custom module directory (like node_modules)
* @param {string} path - Path to custom module directory
*/
function addPath(path);Check if a path matches a given alias pattern.
/**
* Check if a path matches a given alias pattern
* @param {string} path - Path to test
* @param {string} alias - Alias pattern to match against
* @returns {boolean} - True if path matches the alias
*/
function isPathMatchesAlias(path, alias);Reset all registered aliases and custom module paths (primarily for testing).
/**
* Reset all registered aliases and custom module paths
* Note: This function is undocumented and intended for testing purposes only
*/
function reset();Define aliases in your package.json for automatic registration:
{
"_moduleAliases": {
"@root": ".",
"@src": "src/",
"@components": "src/components/",
"@utils": "src/utils/",
"custom-name": "path/to/module"
}
}Define custom module directories that work like node_modules:
{
"_moduleDirectories": [
"custom_modules",
"src/shared-modules"
]
}The library throws specific errors in certain conditions:
Custom Handler Error: Thrown when a custom handler function returns a falsy or non-string value
moduleAlias.addAlias('@src', () => {
// Returns undefined - will throw error
});
require('@src'); // Throws: "[module-alias] Expecting custom handler function to return path."Package.json Not Found Error: Thrown when package.json cannot be located during initialization
moduleAlias({ base: '/nonexistent/path' });
// Throws: "Unable to find package.json in any of:\n[/nonexistent/path]"Compatible with:
Not compatible with:
Module Alias works by intercepting Node.js's internal module resolution:
Module._resolveFilename to check for registered aliases before normal resolutionModule._nodeModulePaths to include custom directories in the module search pathThe library maintains internal data structures:
moduleAliases: Object storing alias-to-path mappingsmoduleAliasNames: Sorted array of alias names for efficient matchingmodulePaths: Array of custom module directory paths