Skip to content

Commit d26c773

Browse files
committed
feat(cli): add ESM config loader
This is a conventional 'best-effort' approach for loading ESM modules dynamically and dealing with the asynchronicity. With some refactoring of the configuration loader logic, instead `lib/nodejs/esm-utils.js::requireOrImport` could be reutilized deduplicating any logic in regards to handling ESM. ESM support in Node.js is stable and I doubt there will be any major changes to the way it is supported, but still, deduplication is always nice, and there might be some slight adjustments to the Node.js module resolution algorithm (https://nodejs.org/api/esm.html#resolution-algorithm) Implements: #5049
1 parent 639904b commit d26c773

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

lib/cli/config.js

+25
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const utils = require('../utils');
2424
exports.CONFIG_FILES = [
2525
'.mocharc.cjs',
2626
'.mocharc.js',
27+
'.mocharc.mjs',
2728
'.mocharc.yaml',
2829
'.mocharc.yml',
2930
'.mocharc.jsonc',
@@ -49,6 +50,28 @@ const parsers = (exports.parsers = {
4950
return require(filepath);
5051
}
5152
},
53+
esm: filepath => {
54+
let importer;
55+
56+
try {
57+
/**
58+
* @see
59+
* {@link https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#sec-imports
60+
* | ECMAScript Specifications}
61+
*/
62+
importer = new Function('spec', 'return import(spec);');
63+
} catch(_) {
64+
throw new Error(
65+
`unable to load ${filepath}. ` +
66+
'Your current runtime does not support dynamic module imports. ' +
67+
'Please define the configuration with another file type.'
68+
);
69+
}
70+
71+
// fail hard, in case the environment is unable to import the ESM module so
72+
// that the error message is as verbose as possible
73+
importer(filepath);
74+
},
5275
json: filepath =>
5376
JSON.parse(
5477
require('strip-json-comments')(fs.readFileSync(filepath, 'utf8'))
@@ -73,6 +96,8 @@ exports.loadConfig = async filepath => {
7396
config = parsers.yaml(filepath);
7497
} else if (ext === '.js' || ext === '.cjs') {
7598
config = parsers.js(filepath);
99+
} else if (ext === '.mjs') {
100+
config = await parsers.esm(filepath);
76101
} else {
77102
config = parsers.json(filepath);
78103
}

0 commit comments

Comments
 (0)