import-sync
Version:
Synchronously import dynamic ECMAScript Modules similar to CommonJS require. Basic wrapper around esm for compatibility with both ESM and CJS projects in NodeJS.
62 lines • 2.06 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const esm_1 = __importDefault(require("@httptoolkit/esm"));
const files_1 = require("./files");
/**
* Returns an ESM-imported module
*
* @param modulePath absolute path or id of the module to import
* @param options same options as importSync
* @returns the esm imported module
*/
const esmImport = (modulePath, options) => {
const esmRequire = (0, esm_1.default)(module, options.esmOptions);
try {
return esmRequire(modulePath);
}
catch (error) {
throw new Error(`
Failed to import from:
${modulePath}
Options:
${JSON.stringify(options)}
Require error message:
${error.stack}
`);
}
};
/**
* Imports ES6 modules synchronously similar to require in CommonJS
* Can be used in both ES6 and CommonJS projects
*
* @param relativePath - the name or relative path of the module, e.g. ./arrays
* @param {Options} [options] - options as defined in types.ts
* @returns the imported module
*/
const importSync = (id, options = {}) => {
var _a;
const basePath = (_a = options.basePath) !== null && _a !== void 0 ? _a : (0, files_1.getCallerDirname)();
const modulePath = /^\.\.?\//.test(id) ? (0, files_1.findModuleFile)(basePath, id) : id;
const importedModule = esmImport(modulePath, options);
if (Object.keys(importedModule).length > 0) {
return importedModule;
}
// In case CJS shows up as empty, e.g. when importing CommonJS/CommonTS into Jest
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const basicModule = require(modulePath);
/* istanbul ignore next */
if (Object.keys(basicModule).length > 0) {
return basicModule;
}
}
catch (_error) {
/* nothing to do */
}
return importedModule;
};
exports.default = importSync;
//# sourceMappingURL=import.js.map