UNPKG

2.01 kBJavaScriptView Raw
1/**
2 * Utility for resolving a module relative to another module
3 * @author Teddy Katz
4 */
5
6"use strict";
7
8const Module = require("module");
9const path = require("path");
10
11// Polyfill Node's `Module.createRequire` if not present. We only support the case where the argument is a filepath, not a URL.
12const createRequire = (
13
14 // Added in v12.2.0
15 Module.createRequire ||
16
17 // Added in v10.12.0, but deprecated in v12.2.0.
18 Module.createRequireFromPath ||
19
20 // Polyfill - This is not executed on the tests on node@>=10.
21 /* istanbul ignore next */
22 (filename => {
23 const mod = new Module(filename, null);
24
25 mod.filename = filename;
26 mod.paths = Module._nodeModulePaths(path.dirname(filename)); // eslint-disable-line no-underscore-dangle
27 mod._compile("module.exports = require;", filename); // eslint-disable-line no-underscore-dangle
28 return mod.exports;
29 })
30);
31
32module.exports = {
33
34 /**
35 * Resolves a Node module relative to another module
36 * @param {string} moduleName The name of a Node module, or a path to a Node module.
37 *
38 * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
39 * a file rather than a directory, but the file need not actually exist.
40 * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
41 */
42 resolve(moduleName, relativeToPath) {
43 try {
44 return createRequire(relativeToPath).resolve(moduleName);
45 } catch (error) {
46 if (
47 typeof error === "object" &&
48 error !== null &&
49 error.code === "MODULE_NOT_FOUND" &&
50 !error.requireStack &&
51 error.message.includes(moduleName)
52 ) {
53 error.message += `\nRequire stack:\n- ${relativeToPath}`;
54 }
55 throw error;
56 }
57 }
58};