relative-module-resolver.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Utility for resolving a module relative to another module
  3. * @author Teddy Katz
  4. */
  5. import Module from "node:module";
  6. /*
  7. * `Module.createRequire` is added in v12.2.0. It supports URL as well.
  8. * We only support the case where the argument is a filepath, not a URL.
  9. */
  10. const createRequire = Module.createRequire;
  11. /**
  12. * Resolves a Node module relative to another module
  13. * @param {string} moduleName The name of a Node module, or a path to a Node module.
  14. * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
  15. * a file rather than a directory, but the file need not actually exist.
  16. * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
  17. * @throws {Error} When the module cannot be resolved.
  18. */
  19. function resolve(moduleName, relativeToPath) {
  20. try {
  21. return createRequire(relativeToPath).resolve(moduleName);
  22. } catch (error) {
  23. // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
  24. if (
  25. typeof error === "object" &&
  26. error !== null &&
  27. error.code === "MODULE_NOT_FOUND" &&
  28. !error.requireStack &&
  29. error.message.includes(moduleName)
  30. ) {
  31. error.message += `\nRequire stack:\n- ${relativeToPath}`;
  32. }
  33. throw error;
  34. }
  35. }
  36. export {
  37. resolve
  38. };