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.
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'The resolvePath function follows this resolution order:
sourcePath is already relative (starts with ./ or ../), return unchangednull 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: nullDetails 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:
opts.cwd)// 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 };
}// 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 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();
}
});
}
}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;
}
}The resolution function includes optimizations:
/**
* Performance characteristics:
* - Memoized option normalization (reselect)
* - Fast path for relative imports
* - Minimal file system access
* - Suitable for repeated calls with same options
*/