load-module.js 636 B

123456789101112131415161718192021222324252627
  1. "use strict";
  2. const path = require("path");
  3. module.exports = { loadModule, isModuleNotFoundError };
  4. function loadModule(moduleName) {
  5. try {
  6. const m = require("module");
  7. const cwd = process.cwd();
  8. const relativeTo = path.join(cwd, "__placeholder__.js");
  9. // eslint-disable-next-line node/no-unsupported-features/node-builtins -- ignore
  10. return m.createRequire(relativeTo)(moduleName);
  11. } catch (error) {
  12. if (!isModuleNotFoundError(error)) {
  13. throw error;
  14. }
  15. // ignore
  16. }
  17. return null;
  18. }
  19. function isModuleNotFoundError(error) {
  20. return (
  21. error && typeof error === "object" && error.code === "MODULE_NOT_FOUND"
  22. );
  23. }