Skip to content

Commit

Permalink
change test file loading to be ESM-first
Browse files Browse the repository at this point in the history
FIrst try ESM, and only if that fails, load test file using require.
This enables an ESM loader to have first dibs at transforming the file.
  • Loading branch information
giltayar committed May 21, 2021
1 parent 45fb789 commit 3271ad4
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions lib/esm-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,28 @@ exports.requireOrImport = async 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.
// If Node.js or the community establish a better procedure for that, we can fix this code.
// Another option here would be to always use `import()`, as this also supports CJS, but I would be
// wary of using it for _all_ existing test files, till ESM is fully stable.
try {
return require(file);
return dealWithExports(await formattedImport(file));
} catch (err) {
if (err.code === 'ERR_REQUIRE_ESM') {
return formattedImport(file);
if (
err.code === 'ERR_MODULE_NOT_FOUND' ||
err.code === 'ERR_UNKNOWN_FILE_EXTENSION'
) {
return require(file);
} else {
throw err;
}
}
};

function dealWithExports(module) {
if (module.default) {
return module.default;
} else {
return {...module, default: undefined};
}
}

exports.loadFilesAsync = async (files, preLoadFunc, postLoadFunc) => {
for (const file of files) {
preLoadFunc(file);
Expand Down

0 comments on commit 3271ad4

Please sign in to comment.