create-require.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. const Module = require("module");
  3. // use eval to avoid tripping bundlers
  4. const xrequire = eval("require");
  5. const createRequireFromPath =
  6. Module.createRequire ||
  7. Module.createRequireFromPath ||
  8. ((filename, dir) => {
  9. // https://github.com/nodejs/node/blob/1ae0511b942c01c6e0adff98643d350a395bf101/lib/internal/modules/cjs/loader.js#L748
  10. // https://github.com/nodejs/node/blob/1ae0511b942c01c6e0adff98643d350a395bf101/lib/internal/modules/cjs/helpers.js#L16
  11. const m = new Module(filename);
  12. m.filename = filename;
  13. m.paths = Module._nodeModulePaths(dir);
  14. // don't name this require to avoid tripping bundlers
  15. function _require(request) {
  16. // can't use m.require because there's an internal requireDepth thing
  17. // in the native Module implementation
  18. return xrequire(resolve(request));
  19. }
  20. function resolve(request, options) {
  21. return Module._resolveFilename(request, m, false, options);
  22. }
  23. _require.resolve = resolve;
  24. function paths(request) {
  25. return Module._resolveLookupPaths(request, m, true);
  26. }
  27. resolve.paths = paths;
  28. _require.main = process.mainModule;
  29. _require.extensions = Module._extensions;
  30. _require.cache = Module._cache;
  31. return _require;
  32. });
  33. module.exports = createRequireFromPath;