createRequire.js 693 B

12345678910111213141516171819202122232425
  1. const nativeModule = require(`module`);
  2. module.exports = (filename) => {
  3. // Added in Node v12.2.0
  4. if (nativeModule.createRequire) {
  5. return nativeModule.createRequire(filename);
  6. }
  7. // Added in Node v10.12.0 and deprecated since Node v12.2.0
  8. if (nativeModule.createRequireFromPath) {
  9. return nativeModule.createRequireFromPath(filename);
  10. }
  11. // Polyfill
  12. return _createRequire(filename);
  13. };
  14. // Polyfill
  15. function _createRequire (filename) {
  16. const mod = new nativeModule.Module(filename, null)
  17. mod.filename = filename
  18. mod.paths = nativeModule.Module._nodeModulePaths(path.dirname(filename))
  19. mod._compile(`module.exports = require;`, filename)
  20. return mod.exports
  21. }