Skip to content
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

fix: esm json import #416

Merged
merged 10 commits into from
Nov 14, 2021
Merged
Changes from 1 commit
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
Next Next commit
fix: esm json import
  • Loading branch information
jly36963 committed Oct 10, 2021
commit af9b265714286c676714e5256b2554afc12bcd52
7 changes: 5 additions & 2 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@
*/

import { format } from 'util'
import { readFileSync } from 'fs'
import { normalize, resolve } from 'path'
import { ArgsInput, Arguments, Parser, Options, DetailedArguments } from './yargs-parser-types.js'
import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'
import { YargsParser } from './yargs-parser.js'
import { createRequire } from "module";

// Addresses: https://github.com/yargs/yargs/issues/2040
const esmRequire = createRequire(import.meta.url);

// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
Expand Down Expand Up @@ -42,7 +45,7 @@ const parser = new YargsParser({
if (typeof require !== 'undefined') {
return require(path)
} else if (path.match(/\.json$/)) {
return readFileSync(path, 'utf8')
return esmRequire(path)
Copy link
Member

Choose a reason for hiding this comment

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

It would be good to add one test that exercises this line.

Perhaps we can add a yargs-parser.mjs test to exercise this path? I believe it might also be good to add a test in yargs-parser.cjs, to confirm that we haven't broken JSON importing for CommonJS.

} else {
throw Error('only .json config files are supported in ESM')
}
Expand Down