Skip to content

feature/ESM configuration file #5397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/cli/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const utils = require('../utils');
exports.CONFIG_FILES = [
'.mocharc.cjs',
'.mocharc.js',
'.mocharc.mjs',
'.mocharc.yaml',
'.mocharc.yml',
'.mocharc.jsonc',
Expand Down Expand Up @@ -64,13 +65,16 @@ const parsers = (exports.parsers = {
* @returns {Object} Parsed config object
*/
exports.loadConfig = filepath => {
const packageJson = require(path.resolve(utils.cwd(), 'package.json'));
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if there's a better / more idiomatic way in Mocha to get the user's package.json file?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would personally use something like package-up

But, determining whether the caller is CJS or ESM can be more tricky than that. My instinct is it'd be best to not add in specific logic for either. Using require(esm), we can do something simpler like packageJson.default ?? packageJson and call it a day.

let config = {};
debug('loadConfig: trying to parse config at %s', filepath);

const ext = path.extname(filepath);
try {
if (ext === '.yml' || ext === '.yaml') {
config = parsers.yaml(filepath);
} else if ((ext === '.js' && packageJson.type === "module") || ext === '.mjs') {
config = parsers.js(filepath).default;
} else if (ext === '.js' || ext === '.cjs') {
config = parsers.js(filepath);
} else {
Expand Down