requireOrImportModule.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = requireOrImportModule;
  6. function _path() {
  7. const data = require('path');
  8. _path = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _url() {
  14. const data = require('url');
  15. _url = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. var _interopRequireDefault = _interopRequireDefault2(
  21. require('./interopRequireDefault')
  22. );
  23. function _interopRequireDefault2(obj) {
  24. return obj && obj.__esModule ? obj : {default: obj};
  25. }
  26. /**
  27. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  28. *
  29. * This source code is licensed under the MIT license found in the
  30. * LICENSE file in the root directory of this source tree.
  31. */
  32. async function requireOrImportModule(
  33. filePath,
  34. applyInteropRequireDefault = true
  35. ) {
  36. if (!(0, _path().isAbsolute)(filePath) && filePath[0] === '.') {
  37. throw new Error(
  38. `Jest: requireOrImportModule path must be absolute, was "${filePath}"`
  39. );
  40. }
  41. try {
  42. const requiredModule = require(filePath);
  43. if (!applyInteropRequireDefault) {
  44. return requiredModule;
  45. }
  46. return (0, _interopRequireDefault.default)(requiredModule).default;
  47. } catch (error) {
  48. if (error.code === 'ERR_REQUIRE_ESM') {
  49. try {
  50. const moduleUrl = (0, _url().pathToFileURL)(filePath); // node `import()` supports URL, but TypeScript doesn't know that
  51. const importedModule = await import(moduleUrl.href);
  52. if (!applyInteropRequireDefault) {
  53. return importedModule;
  54. }
  55. if (!importedModule.default) {
  56. throw new Error(
  57. `Jest: Failed to load ESM at ${filePath} - did you use a default export?`
  58. );
  59. }
  60. return importedModule.default;
  61. } catch (innerError) {
  62. if (innerError.message === 'Not supported') {
  63. throw new Error(
  64. `Jest: Your version of Node does not support dynamic import - please enable it or use a .cjs file extension for file ${filePath}`
  65. );
  66. }
  67. throw innerError;
  68. }
  69. } else {
  70. throw error;
  71. }
  72. }
  73. }