Question:I’m trying to setup a very simple NPM codebase that I can use to drive an API to do some testing.
The line of code causing the error is just
import fetch from "node-fetch";, see the code.
For the setup/configuration, I’m following this repository (suggestions for a better template to use would be appreciated): https://github.com/bromix/typescript-jest-example
When I try to use the
node-fetchlibrary in my code (either in a
test.tsfile in the
/testdirectory or a
.tsfile in the
/srcdirectory) – I get the following error:
But I’ve tried frobbing a bunch of different things in
tsconfig.jsonbut I can’t get it work.
What change do I need to make so my tests can use
node-fetchto make request calls?
The whole point of the repo is just to make these HTTP calls, so there’s no compatibility problems to consider with changing module type or whatever needs doing.
My workaround is to downgrade to
2.6.7as shown here. But if this esmodule stuff is the way forward, I’d like to figure out how to make it work.
You can see the entire failing project here: https://github.com/ardc-shorn/rats/tree/0cdf2cf1ff4bc9e7ef0fa6113db9b9ff9f6cc6c9
But, to have a self-cointained question, here’s the important config.
Answer:Your project isn’t an ECMAScript-Module, so you are unable to resolve them. The only exception is if they include an alternate build for CJS, or whatever pre-ESM module type your using. Its actually pretty easy to figure this out with a quick DDG/Google search.
In reference 2 my Pre-ESM comment: your using CJS, as a consequence; you can only use an ESM package if it contains a transpiled CJS build (I guess they could hand write them both, but why?). Any package that does this will clearly state that they support both ESM & CJS in their package’s docs (README.md file). If for some reason you want to check another way than their docs, you would be able to quickly tell by looking at any package.json files the project contains. A quick sign is seeing more than one package.json file, &/or seing an “exports” property in the package.json
If you have better answer, please add a comment about this, thank you!