json-schema-ref-parser icon indicating copy to clipboard operation
json-schema-ref-parser copied to clipboard

Importing individual method fails with "Class is not a constructor"

Open silverwind opened this issue 6 years ago • 5 comments
trafficstars

I'd like to import only the dereference method (the other parts of this module should ideally be tree-shaken out), but it seems this is currently not possible because of this error:

> const {dereference} = require("json-schema-ref-parser")
> dereference({}).then(console.log)
Thrown:
TypeError: Class is not a constructor
    at $RefParser.dereference (node_modules/json-schema-ref-parser/lib/index.js:227:18)

Importing the default export works as expected in comparison:

> const parser = require("json-schema-ref-parser")
> parser.dereference({}).then(console.log)
{}

silverwind avatar Oct 04 '19 06:10 silverwind

Is this code of any help? https://github.com/APIDevTools/json-schema-ref-parser/issues/14#issuecomment-698530729

philsturgeon avatar Jan 15 '21 11:01 philsturgeon

That example includes a path-based import which would break when the referenced file is moved. I would not consider it a stable interface.

silverwind avatar Jan 15 '21 12:01 silverwind

Yes this is a workaround not a complete solution.

philsturgeon avatar Jan 15 '21 15:01 philsturgeon

json-schema-ref-parser now always fails on TypeScript 4.4 with the same error.

The underlying issue is this: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-4.html#more-compliant-indirect-calls-for-imported-functions

By spec, you cannot bind an exported method, which is causing the code to error on node_modules/@apidevtools/json-schema-ref-parser/lib/index.js:160:

let Class = this; // eslint-disable-line consistent-this
let instance = new Class();

For anyone struggling to get this working, here's a hacky workaround:

import $RefParser from '@apidevtools/json-schema-ref-parser';
$RefParser.dereference = $RefParser.dereference.bind($RefParser);
$RefParser.resolve = $RefParser.resolve.bind($RefParser);

KurtPreston avatar Oct 11 '21 22:10 KurtPreston

Anyone able to get a pull request over to fix this? Or is it not a problem anymore?

philsturgeon avatar Nov 26 '22 13:11 philsturgeon