3

I have built a class to do some fetch from an API and construct a suited response for my app.

I use this file both in an app that run on the browser, and on a CLI app to work on the terminal.

As I built the browser app first, there was no import to node-fetch. Now when I try to use this .js file in my CLI app, it returns error saying fetch is not defined.

If I add to my api client .js file: import fetch from "node-fetch" then now my browser app is not working as well, print to the console:

Uncaught TypeError: Failed to resolve module specifier "node-fetch". Relative references must start with either "/", "./", or "../".

Is there anyway to apply fetch and use the same file for both?

Thanks

2

3 Answers 3

3

For use-cases where you cannot update Node, you can conditionally import the Fetch API.

let fetch = globalThis?.fetch;

if (!fetch && process?.versions?.node) {
  fetch = (await import('node-fetch')).default;
}

console.log(fetch);

Note that this uses top-level await.

Sign up to request clarification or add additional context in comments.

Comments

1

Your options are:

The former option is much easier (at least from a technical POV)!

Comments

1

When using NodeJS, fetch is not an actual thing. I'd definitely replace that with the Axios module as shown below:

const axios = require('axios');

axios.get(link).then(response => {
  // ...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.