or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdindex.mdresolve-path.md
tile.json

resolve-path.mddocs/

Path Resolution API

External API for plugin authors and tools that need to resolve paths using the same logic as the Babel plugin. This allows other tools to integrate with the module resolution system.

Capabilities

resolvePath Function

The main path resolution function exposed for external use.

/**
 * Resolves module paths using plugin configuration
 * @param sourcePath - The module specifier to resolve (e.g., 'components/Button')
 * @param currentFile - Absolute or relative path to the file containing the import
 * @param opts - Plugin configuration options
 * @returns Resolved path string, or null if no resolution found
 */
function resolvePath(
  sourcePath: string,
  currentFile: string,
  opts?: PluginOptions
): string | null;

Import Statement:

const { resolvePath } = require('babel-plugin-module-resolver');
// or
import { resolvePath } from 'babel-plugin-module-resolver';

Usage Examples:

const { resolvePath } = require('babel-plugin-module-resolver');

// Basic usage with options
const resolved = resolvePath('components/Button', '/project/src/pages/Home.js', {
  root: ['./src'],
  alias: {
    'components': './src/components'
  }
});
// Result: './components/Button' (relative to /project/src/pages/)

// Usage in a plugin or tool
const pluginOptions = {
  root: ['./src'],
  alias: {
    'utils': './src/utilities',
    '@': './src'
  },
  extensions: ['.js', '.jsx', '.ts']
};

const resolved = resolvePath('@/components/Header', '/project/src/App.js', pluginOptions);
// Result: './components/Header'

Resolution Strategy

The resolvePath function follows this resolution order:

  1. Skip relative paths: If sourcePath is already relative (starts with ./ or ../), return unchanged
  2. Alias resolution: Try to match against configured aliases (exact matches and regex patterns)
  3. Root resolution: Search within configured root directories
  4. No match: Return null if no resolution is found
/**
 * Resolution behavior for different input types:
 * - Relative paths (./file, ../file): Returned unchanged
 * - Absolute-style paths: Resolved using aliases and roots
 * - Node modules: Can be aliased to different modules
 * - Returns null: When no resolution rule matches
 */

Examples:

const opts = {
  root: ['./src'],
  alias: {
    'components': './src/components',
    'lodash': 'underscore'
  }
};

// Relative paths pass through unchanged
resolvePath('./Button', '/project/src/App.js', opts);
// Returns: './Button'

// Alias resolution
resolvePath('components/Button', '/project/src/App.js', opts);
// Returns: './components/Button'

// Node module aliasing
resolvePath('lodash', '/project/src/utils.js', opts);
// Returns: 'underscore'

// Root resolution (no alias match)
resolvePath('utilities/helpers', '/project/src/App.js', opts);
// Returns: './utilities/helpers' (if file exists in src/)

// No match
resolvePath('unknown-module', '/project/src/App.js', opts);
// Returns: null

Path Parameters

Details about the function parameters:

/**
 * @param sourcePath - Module specifier to resolve
 *   Examples: 'components/Button', '@/utils', 'lodash', './file'
 * @param currentFile - File path (absolute or relative to CWD)
 *   Examples: '/absolute/path/to/file.js', 'src/components/App.js'
 * @param opts - Configuration options (same as plugin options)
 */

currentFile parameter behavior:

  • Absolute paths: Used directly for resolution calculations
  • Relative paths: Resolved relative to current working directory (not opts.cwd)
  • Special value 'unknown': When file context is unavailable

Integration Examples

ESLint Plugin Integration

// eslint-import-resolver-babel-module usage
const { resolvePath } = require('babel-plugin-module-resolver');

function resolve(source, file, config) {
  const resolved = resolvePath(source, file, config);
  return resolved ? { found: true, path: resolved } : { found: false };
}

IDE/Editor Integration

// Tool for IDE autocompletion
const { resolvePath } = require('babel-plugin-module-resolver');

function getModulePath(importPath, currentFile, babelConfig) {
  // Extract module-resolver config from babel config
  const moduleResolverConfig = extractModuleResolverConfig(babelConfig);
  
  const resolved = resolvePath(importPath, currentFile, moduleResolverConfig);
  return resolved;
}

Custom Bundler Plugin

// Custom webpack resolver
const { resolvePath } = require('babel-plugin-module-resolver');

class BabelModuleResolverPlugin {
  apply(resolver) {
    resolver.getHook('resolve').tapAsync('BabelModuleResolver', (request, resolveContext, callback) => {
      const resolved = resolvePath(
        request.request,
        request.path,
        this.options
      );
      
      if (resolved) {
        // Continue with resolved path
        resolver.doResolve(target, { ...request, request: resolved }, callback);
      } else {
        callback();
      }
    });
  }
}

Error Handling

The function handles errors gracefully:

/**
 * Error handling behavior:
 * - Invalid options: Uses safe defaults
 * - File system errors: Continues with remaining resolution strategies
 * - Invalid paths: Returns null
 * - Missing dependencies: Logs warnings (unless loglevel is 'silent')
 */

Example:

// Safe usage with error handling
function safeResolve(sourcePath, currentFile, opts) {
  try {
    const result = resolvePath(sourcePath, currentFile, opts);
    return result || sourcePath; // Fallback to original path
  } catch (error) {
    console.warn('Resolution failed:', error.message);
    return sourcePath;
  }
}

Performance Considerations

The resolution function includes optimizations:

  • Memoization: Options are normalized using reselect library for efficient caching based on currentFile and opts parameters
  • Early returns: Relative paths skip processing entirely
  • Lazy evaluation: File system checks only when needed during root resolution
/**
 * Performance characteristics:
 * - Memoized option normalization (reselect)
 * - Fast path for relative imports
 * - Minimal file system access
 * - Suitable for repeated calls with same options
 */