or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-module-alias

Create aliases of directories and register custom module paths in Node.js

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/module-alias@2.2.x

To install, run

npx @tessl/cli install tessl/npm-module-alias@2.2.0

index.mddocs/

Module Alias

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.

Package Information

  • Package Name: module-alias
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install module-alias

Core Imports

Main 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.

Basic Usage

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 directory

Programmatic 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');

Architecture

Module Alias is built around Node.js's internal module resolution system and consists of several key components:

  • Module Resolution Hooks: Intercepts Node.js's Module._resolveFilename method to check registered aliases before normal module resolution
  • Path Resolution System: Modifies Module._nodeModulePaths to include custom directories in the module search path
  • Alias Registry: Maintains sorted arrays and objects for efficient alias matching during module resolution
  • Configuration Parser: Reads package.json configuration and converts relative paths to absolute paths
  • Custom Handler System: Supports function-based aliases for dynamic path resolution based on calling context

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.

Capabilities

Initialization

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:
    • String: Direct path to directory containing package.json (shorthand for {base: string})
    • Object: Configuration object with properties:
      • base (string): Base directory path for resolving relative alias paths

Behavior:

  • If no options provided, searches for package.json in current working directory or two levels up from node_modules
  • Reads _moduleAliases and _moduleDirectories from package.json
  • Converts relative alias paths to absolute paths using the base directory

Alias Management

Register 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';
});

Custom Module Paths

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);

Path Matching

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

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();

Package.json Configuration

Module Aliases

Define aliases in your package.json for automatic registration:

{
  "_moduleAliases": {
    "@root": ".",
    "@src": "src/",
    "@components": "src/components/",
    "@utils": "src/utils/",
    "custom-name": "path/to/module"
  }
}
  • Keys are the alias names (can start with @ or be any string)
  • Values are relative paths from the package.json location
  • Absolute paths (starting with /) are used as-is

Custom Module Directories

Define custom module directories that work like node_modules:

{
  "_moduleDirectories": [
    "custom_modules",
    "src/shared-modules"
  ]
}
  • Array of directory names/paths
  • These directories will be searched for modules like node_modules
  • "node_modules" should not be included (it's automatically handled)

Error Handling

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]"

Compatibility

Compatible with:

  • All Node.js versions
  • CommonJS and ES6 imports (via transpilation)
  • require.resolve()

Not compatible with:

  • Front-end JavaScript frameworks (use Webpack's resolve.alias instead)
  • Jest testing framework (use Jest's moduleNameMapper instead)
  • NCC compiler
  • Browser environments

Implementation Details

Module Alias works by intercepting Node.js's internal module resolution:

  • Alias Resolution: Modifies Module._resolveFilename to check for registered aliases before normal resolution
  • Custom Paths: Modifies Module._nodeModulePaths to include custom directories in the module search path
  • Performance: Aliases are sorted for efficient matching during resolution

The library maintains internal data structures:

  • moduleAliases: Object storing alias-to-path mappings
  • moduleAliasNames: Sorted array of alias names for efficient matching
  • modulePaths: Array of custom module directory paths