relative-module-resolver.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Utility for resolving a module relative to another module
  3. * @author Teddy Katz
  4. */
  5. import Module from "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. */
  18. function resolve(moduleName, relativeToPath) {
  19. try {
  20. return createRequire(relativeToPath).resolve(moduleName);
  21. } catch (error) {
  22. // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
  23. if (
  24. typeof error === "object" &&
  25. error !== null &&
  26. error.code === "MODULE_NOT_FOUND" &&
  27. !error.requireStack &&
  28. error.message.includes(moduleName)
  29. ) {
  30. error.message += `\nRequire stack:\n- ${relativeToPath}`;
  31. }
  32. throw error;
  33. }
  34. }
  35. export {
  36. resolve
  37. };