require-or-import.js 981 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. var pathToFileURL = require('url').pathToFileURL;
  3. var importESM;
  4. try {
  5. // Node.js <10 errors out with a SyntaxError when loading a script that uses import().
  6. // So a function is dynamically created to catch the SyntaxError at runtime instead of parsetime.
  7. // That way we can keep supporting all Node.js versions all the way back to 0.10.
  8. importESM = new Function('id', 'return import(id);');
  9. } catch (e) {
  10. importESM = null;
  11. }
  12. function requireOrImport(path, callback) {
  13. var err = null;
  14. var cjs;
  15. try {
  16. cjs = require(path);
  17. } catch (e) {
  18. if (pathToFileURL && importESM && e.code === 'ERR_REQUIRE_ESM') {
  19. // This is needed on Windows, because import() fails if providing a Windows file path.
  20. var url = pathToFileURL(path);
  21. importESM(url).then(function(esm) { callback(null, esm); }, callback);
  22. return;
  23. }
  24. err = e;
  25. }
  26. process.nextTick(function() { callback(err, cjs); });
  27. }
  28. module.exports = requireOrImport;