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
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions lib/index.ts
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
2 changes: 1 addition & 1 deletion tsconfig.json
Expand Up @@ -6,7 +6,7 @@
"sourceMap": false,
"target": "es2017",
"moduleResolution": "node",
"module": "es2015"
"module": "es2020"
},
"include": [
"lib/**/*.ts"
Expand Down