relative-module-resolver.js 1.0 KB

12345678910111213141516171819202122232425262728
  1. /**
  2. * Utility for resolving a module relative to another module
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. const Module = require("node:module");
  7. /*
  8. * `Module.createRequire` is added in v12.2.0. It supports URL as well.
  9. * We only support the case where the argument is a filepath, not a URL.
  10. */
  11. const createRequire = Module.createRequire;
  12. /**
  13. * Resolves a Node module relative to another module
  14. * @param {string} moduleName The name of a Node module, or a path to a Node module.
  15. * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
  16. * a file rather than a directory, but the file need not actually exist.
  17. * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
  18. * @throws {Error} When the module cannot be resolved.
  19. */
  20. function resolve(moduleName, relativeToPath) {
  21. return createRequire(relativeToPath).resolve(moduleName);
  22. }
  23. exports.resolve = resolve;