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
The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import
so this should do a conditional import on supported node versions:
let fetch = fetch ?? await import('node-fetch')