Rudolfs Bundulis
Rudolfs Bundulis

Reputation: 11954

using fetch in shared javascript module

I have a shared javascript module that I am trying to import in both vue based frontend built with webpack and a node.js cli script. Initially the shared code was a part of the frontend (thus used fetch) and now I am trying to reuse it in the node.js cli script. So I stumbled upon fetch being unavailalble, which makes sense, but what I don't get is what are the options here. What I considered:

  1. I tried importing fetch from node-fetch on the first line of the cli script via import fetch from 'node-fetch' and hoped that it will be exposed to the shared code imported later on but that does not work (ok that was a long shot and a naive hope). Is there a way to somehow provide globals to a script imported later on, or that is not an existent feature?
  2. I tried conditional imports - defining some variable, e.g. APP_ENV in webpack and then conditionally import fetch but that also failed - webpack failed with 'import' and 'export' may only appear at the top level when I did this:
if (APP_ENV !== 'browser') {
    import fetch from 'node-fetch'
}

Is the only option here using axios or some other request library in the shared code, or can I make either of options listed above work?

Upvotes: 0

Views: 479

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

You can do a conditional import with top-level await and dynamic import(), both of which are supported by Webpack.

For instance:

const localFetch = typeof fetch === "function"
    ? fetch
    : await import("node-Fetch").then(mod => mod.default);

That uses the global fetch if it exists, node-fetch's default export if it doesn't (making the assumption that it's running on Node.js).

Upvotes: 1

user2258152
user2258152

Reputation: 675

You can check if the window object is defined
https://developer.mozilla.org/en-US/docs/Web/API/Window/window
If it's not defined you can asume that you are using Node

Assign the fetch function from node-fetch to a Node global variable https://nodejs.org/api/globals.html#globals_global

import fetch from 'node-fetch'
if (typeof window === 'undefined') {
  global.fetch = fetch // you can use fetch() anywhere in Node (really useful for server side rendering)
}

Upvotes: 1

Related Questions