Iconify for Svelte function: setFetch

This tutorial is part of Iconify for Svelte functions tutorial.

Function setFetch() can be used to load Fetch API implementation.

Why is it needed?

When using icon component in a browser, it relies on fetch() to retrieve data from Iconify API.

All modern browsers support it.

Currently Node.js does not natively support Fetch API. It is available in Node.js version 17 using flag "--experimental-fetch", but without it Fetch API is not available. That means icon component cannot retrieve icon data from Iconify API when used on a server side in Node.js environment.

Usage

Function has the following parameter:

  • fetch. Function fetch().

Steps

  1. Install cross-fetch (if you are using CommonJS) or node-fetch (if you are using modules) as dependency.
  2. Use internal setFetch() function to set third party Fetch API before using any icon component functions.
import { _api } from '@iconify/svelte';
import fetch from 'cross-fetch';
//  import fetch from 'node-fetch';

// Set Fetch API before doing anything
_api.setFetch(fetch);

This code must be added only to script that runs on server side, not bundled for client side use. Browsers already support Fetch API, so this code is not needed in browsers.