Search code examples
javascriptnpmpolyfillsfetch-api

How to use the GitHub Fetch API polyfill


I would like to use a polyfill for fetch() so that my code runs on Safari using the GitHub Fetch Polyfill, but I'm not sure how to use it.

According to its documentation, I can install it with:

$ npm install whatwg-fetch --save

I have done this step.

I've already tried this, but it does not work:

var fetch = require('whatwg-fetch') // does not work

How am I suppose to use the fetch polyfill?


References:


Solution

  • First, install using

    npm install --save whatwg-fetch
    

    then use:

    require('whatwg-fetch')
    

    You can alternatively use import syntax

    import 'whatwg-fetch'
    

    The above method will require you to use browserify.

    Another way (without requiring browserify) is to download the fetch.js file and place it in your project folder and then in your index.html use:

    <script src="fetch.js"></script>