From ed1f4a0a354c63a2ceaa087d08a870159b6f54db Mon Sep 17 00:00:00 2001 From: Gil Tayar Date: Sat, 22 May 2021 17:31:01 +0300 Subject: [PATCH] bring back support for Node <= 12.22.0 --- lib/esm-utils.js | 58 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 16 deletions(-) diff --git a/lib/esm-utils.js b/lib/esm-utils.js index a79aeca74c..2aa9fe674a 100644 --- a/lib/esm-utils.js +++ b/lib/esm-utils.js @@ -30,23 +30,32 @@ const formattedImport = async file => { return import(file); }; -exports.requireOrImport = async file => { - if (path.extname(file) === '.mjs') { - return formattedImport(file); - } - try { - return dealWithExports(await formattedImport(file)); - } catch (err) { - if ( - err.code === 'ERR_MODULE_NOT_FOUND' || - err.code === 'ERR_UNKNOWN_FILE_EXTENSION' - ) { - return require(file); - } else { - throw err; +const hasStableEsmImplementation = (() => { + const [major, minor] = process.version.split('.'); + // ESM is stable from v12.22.0 onward + // https://nodejs.org/api/esm.html#esm_modules_ecmascript_modules + return parseInt(major.slice(1), 10) > 12 || parseInt(minor, 10) >= 22; +})(); + +exports.requireOrImport = hasStableEsmImplementation + ? async file => { + if (path.extname(file) === '.mjs') { + return formattedImport(file); + } + try { + return dealWithExports(await formattedImport(file)); + } catch (err) { + if ( + err.code === 'ERR_MODULE_NOT_FOUND' || + err.code === 'ERR_UNKNOWN_FILE_EXTENSION' + ) { + return require(file); + } else { + throw err; + } + } } - } -}; + : implemenetationOfRequireOrImportForUnstableEsm; function dealWithExports(module) { if (module.default) { @@ -63,3 +72,20 @@ exports.loadFilesAsync = async (files, preLoadFunc, postLoadFunc) => { postLoadFunc(file, result); } }; + +async function implemenetationOfRequireOrImportForUnstableEsm(file) { + if (path.extname(file) === '.mjs') { + return formattedImport(file); + } + // This is currently the only known way of figuring out whether a file is CJS or ESM in + // Node.js that doesn't necessitate calling `import` first. + try { + return require(file); + } catch (err) { + if (err.code === 'ERR_REQUIRE_ESM') { + return formattedImport(file); + } else { + throw err; + } + } +}