Conditional import with ES Module ( fetch / node-fetch )

Viewed 115

I'm writting a JS code that can be use eather for Node application or for JavaScript web browser application.

Since Node 17.5 it's now possible to use the native fetch API from JavaScript.

I wonder if there is a way to use a kind of conditinal import for ES Module working like this :

if fetch exist => use fetch
else import fetch from node-fetch

I've tried something like this :

if(!fetch) {
    import fetch from 'node-fetch'
}

...
fetch(url).then(res => ...)
...

But it raises an error as fetch is undefined. Note: I made my test using node@18

Has someone an idea to solve my probleme ?

Answer :

I Found a solution thanks to @Positivity's answer :

let fetcher = fetch ?? await import('node-fetch');

Then I use fetcher as fetch.
If I rename the variable to fetch it throw an error :

Cannot access 'fetch' before initialization

Finnaly found a solution to this error :

if(!fetch) {
    const fetch = await import('node-fetch');
}
// else => fetch is already declared
1 Answers
Related