UNPKG

2.97 kBJavaScriptView Raw
1/**
2 * @fileoverview Implements the Node.js require.resolve algorithm
3 * @author Nicholas C. Zakas
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const Module = require("module");
13
14//------------------------------------------------------------------------------
15// Private
16//------------------------------------------------------------------------------
17
18const DEFAULT_OPTIONS = {
19
20 /*
21 * module.paths is an array of paths to search for resolving things relative
22 * to this file. Module.globalPaths contains all of the special Node.js
23 * directories that can also be searched for modules.
24 *
25 * Need to check for existence of module.paths because Jest seems not to
26 * include it. See https://github.com/eslint/eslint/issues/5791.
27 */
28 lookupPaths: module.paths ? module.paths.concat(Module.globalPaths) : Module.globalPaths.concat()
29};
30
31/**
32 * Resolves modules based on a set of options.
33 */
34class ModuleResolver {
35
36 /**
37 * Resolves modules based on a set of options.
38 * @param {Object} options The options for resolving modules.
39 * @param {string[]} options.lookupPaths An array of paths to include in the
40 * lookup with the highest priority paths coming first.
41 */
42 constructor(options) {
43 this.options = Object.assign({}, DEFAULT_OPTIONS, options || {});
44 }
45
46 /**
47 * Resolves the file location of a given module relative to the configured
48 * lookup paths.
49 * @param {string} name The module name to resolve.
50 * @param {string} extraLookupPath An extra path to look into for the module.
51 * This path is used with the highest priority.
52 * @returns {string} The resolved file path for the module.
53 * @throws {Error} If the module cannot be resolved.
54 */
55 resolve(name, extraLookupPath) {
56
57 /*
58 * First, clone the lookup paths so we're not messing things up for
59 * subsequent calls to this function. Then, move the extraLookupPath to the
60 * top of the lookup paths list so it will be searched first.
61 */
62 const lookupPaths = [extraLookupPath, ...this.options.lookupPaths];
63
64 /**
65 * Module._findPath is an internal method to Node.js, then one they use to
66 * lookup file paths when require() is called. So, we are hooking into the
67 * exact same logic that Node.js uses.
68 */
69 const result = Module._findPath(name, lookupPaths); // eslint-disable-line no-underscore-dangle
70
71 if (!result) {
72 throw new Error(`Cannot find module '${name}'`);
73 }
74
75 return result;
76 }
77}
78
79//------------------------------------------------------------------------------
80// Public API
81//------------------------------------------------------------------------------
82
83module.exports = ModuleResolver;