2 * Utility for resolving a module relative to another module
8 const Module = require("module");
9 const path = require("path");
11 // Polyfill Node's `Module.createRequire` if not present. We only support the case where the argument is a filepath, not a URL.
12 const createRequire = (
15 Module.createRequire ||
17 // Added in v10.12.0, but deprecated in v12.2.0.
18 Module.createRequireFromPath ||
20 // Polyfill - This is not executed on the tests on node@>=10.
21 /* istanbul ignore next */
23 const mod = new Module(filename, null);
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
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.
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`
42 resolve(moduleName, relativeToPath) {
44 return createRequire(relativeToPath).resolve(moduleName);
47 typeof error === "object" &&
49 error.code === "MODULE_NOT_FOUND" &&
50 !error.requireStack &&
51 error.message.includes(moduleName)
53 error.message += `\nRequire stack:\n- ${relativeToPath}`;