create-require.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const nativeModule = require('module')
  2. const path = require('path')
  3. const fs = require('fs')
  4. function createRequire (filename) {
  5. // Fallback to process.cwd() if no filename passed
  6. if (!filename) {
  7. filename = process.cwd()
  8. }
  9. // If filename is dir, createRequire goes with parent directory, so we need fakepath
  10. if (isDir(filename)) {
  11. filename = path.join(filename, 'index.js')
  12. }
  13. // Added in Node v12.2.0
  14. if (nativeModule.createRequire) {
  15. return nativeModule.createRequire(filename)
  16. }
  17. // Added in Node v10.12.0 and deprecated since Node v12.2.0
  18. if (nativeModule.createRequireFromPath) {
  19. return nativeModule.createRequireFromPath(filename)
  20. }
  21. // Polyfill
  22. return _createRequire(filename)
  23. }
  24. // Polyfill
  25. function _createRequire (filename) {
  26. const mod = new nativeModule.Module(filename, null)
  27. mod.filename = filename
  28. mod.paths = nativeModule.Module._nodeModulePaths(path.dirname(filename))
  29. mod._compile('module.exports = require;', filename)
  30. return mod.exports
  31. }
  32. function isDir (path) {
  33. try {
  34. const stat = fs.lstatSync(path)
  35. return stat.isDirectory()
  36. } catch (e) {
  37. // lstatSync throws an error if path doesn't exist
  38. return false
  39. }
  40. }
  41. module.exports = createRequire