Just a note for anyone googling this (I had a hard time...):
This syntax is used in DefinitelyTyped tests:
import nock = require('nock');
However, it doesn't work with Babel (in our case, Jest uses Babel under the covers):
SyntaxError: example.ts: `import =` is not supported by @babel/plugin-transform-typescript
Please consider using `import <moduleName> from '<moduleName>';` alongside Typescript's --allowSyntheticDefaultImports option.
This is the recommended syntax:
import nock from 'nock';
But that yielded another error when starting the app via ts-node:
example.ts:7
const mockApi = nock('https://example.com');
^
TypeError: nock_1.default is not a function
It started working when I added "esModuleInterop": true to tsconfig.json.
Summary:
import nock from 'nock'"esModuleInterop": true to tsconfig.json(Sorry if this is not the best place to post it but I intuitively searched this repo for "TypeScript" and googled as well, without much luck. Feel free to close.)
There could be discussion around whether we want to support export default too, to help with this issue. As a, primarily, TS dev these days I can appreciate this pain point.
index.js could be updated to have this
const scope = require('./lib/scope')
module.exports = scope
module.exports.default = scope
Would be a welcome change for sure 馃槃
... and to extend on @borekb summary:
"esModuleInterop": true should be the go to for any TS app especially for an new app. If, however, you have an existing codebase where turning on esModuleInterop would be a pain, the alternative is to import using: import * as nock from "nock"; to get the same results.
the alternative is to import using:
import * as nock from "nock";to get the same results.
That's the first thing I usually try but it doesn't work for me:
TypeError: nock is not a function
Again, this is in the context of Babel (Jest tests). It works via ts-node.
index.js could be updated to have this
const scope = require('./lib/scope') module.exports = scope module.exports.default = scope
Hmm, this seems a bit hacky solution for this problem which is an ecosystem issue.
Is it possible there is a problem with the types that is contributing to the difficulty with import nock from "nock"?
import nock from "nock" is importing a default export, which nock doesn't provide.
It's true that I'm fighting with this because of how Babel + TypeScript play together but it's a significant enough stack & the change for Nock would be small so I think it would be worth it.
Most helpful comment
import nock from "nock"is importing a default export, which nock doesn't provide.It's true that I'm fighting with this because of how Babel + TypeScript play together but it's a significant enough stack & the change for Nock would be small so I think it would be worth it.