2 * Utility for resolving a module relative to another module
8 const Module = require("module");
11 * `Module.createRequire` is added in v12.2.0. It supports URL as well.
12 * We only support the case where the argument is a filepath, not a URL.
14 // eslint-disable-next-line node/no-unsupported-features/node-builtins, node/no-deprecated-api
15 const createRequire = Module.createRequire || Module.createRequireFromPath;
20 * Resolves a Node module relative to another module
21 * @param {string} moduleName The name of a Node module, or a path to a Node module.
22 * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
23 * a file rather than a directory, but the file need not actually exist.
24 * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
26 resolve(moduleName, relativeToPath) {
28 return createRequire(relativeToPath).resolve(moduleName);
31 // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
33 typeof error === "object" &&
35 error.code === "MODULE_NOT_FOUND" &&
36 !error.requireStack &&
37 error.message.includes(moduleName)
39 error.message += `\nRequire stack:\n- ${relativeToPath}`;