GithubHelp home page GithubHelp logo

developit / unfetch Goto Github PK

View Code? Open in Web Editor NEW
5.7K 41.0 198.0 512 KB

๐Ÿ• Bare minimum 500b fetch polyfill.

Home Page: https://npm.im/unfetch

License: MIT License

JavaScript 86.19% TypeScript 13.81%
fetch ajax xmlhttprequest polyfill ponyfill tiny unfetch

unfetch's Introduction

unfetch
npm gzip size downloads travis

unfetch

Tiny 500b fetch "barely-polyfill"

  • Tiny: about 500 bytes of ES3 gzipped
  • Minimal: just fetch() with headers and text/json responses
  • Familiar: a subset of the full API
  • Supported: supports IE8+ (assuming Promise is polyfilled of course!)
  • Standalone: one function, no dependencies
  • Modern: written in ES2015, transpiled to 500b of old-school JS

๐Ÿค” What's Missing?

  • Uses simple Arrays instead of Iterables, since Arrays are iterables
  • No streaming, just Promisifies existing XMLHttpRequest response bodies
  • Use in Node.JS is handled by isomorphic-unfetch


Installation

For use with node and npm:

npm i unfetch

Otherwise, grab it from unpkg.com/unfetch.


Usage: As a Polyfill

This automatically "installs" unfetch as window.fetch() if it detects Fetch isn't supported:

import 'unfetch/polyfill'

// fetch is now available globally!
fetch('/foo.json')
  .then( r => r.json() )
  .then( data => console.log(data) )

This polyfill version is particularly useful for hotlinking from unpkg:

<script src="https://unpkg.com/unfetch/polyfill"></script>
<script>
  // now our page can use fetch!
  fetch('/foo')
</script>

Usage: As a Ponyfill

With a module bundler like rollup or webpack, you can import unfetch to use in your code without modifying any globals:

// using JS Modules:
import fetch from 'unfetch'

// or using CommonJS:
const fetch = require('unfetch')

// usage:
fetch('/foo.json')
  .then( r => r.json() )
  .then( data => console.log(data) )

The above will always return unfetch(). (even if window.fetch exists!)

There's also a UMD bundle available as unfetch/dist/unfetch.umd.js, which doesn't automatically install itself as window.fetch.


Examples & Demos

Real Example on JSFiddle โžก๏ธ

// simple GET request:
fetch('/foo')
  .then( r => r.text() )
  .then( txt => console.log(txt) )


// complex POST request with JSON, headers:
fetch('/bear', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ hungry: true })
}).then( r => {
  open(r.headers.get('location'));
  return r.json();
})

API

While one of Unfetch's goals is to provide a familiar interface, its API may differ from other fetch polyfills/ponyfills. One of the key differences is that Unfetch focuses on implementing the fetch() API, while offering minimal (yet functional) support to the other sections of the Fetch spec, like the Headers class or the Response class. Unfetch's API is organized as follows:

fetch(url: string, options: Object)

This function is the heart of Unfetch. It will fetch resources from url according to the given options, returning a Promise that will eventually resolve to the response.

Unfetch will account for the following properties in options:

  • method: Indicates the request method to be performed on the target resource (The most common ones being GET, POST, PUT, PATCH, HEAD, OPTIONS or DELETE).
  • headers: An Object containing additional information to be sent with the request, e.g. { 'Content-Type': 'application/json' } to indicate a JSON-typed request body.
  • credentials: โš  Accepts a "include" string, which will allow both CORS and same origin requests to work with cookies. As pointed in the 'Caveats' section, Unfetch won't send or receive cookies otherwise. The "same-origin" value is not supported. โš 
  • body: The content to be transmitted in request's body. Common content types include FormData, JSON, Blob, ArrayBuffer or plain text.

response Methods and Attributes

These methods are used to handle the response accordingly in your Promise chain. Instead of implementing full spec-compliant Response Class functionality, Unfetch provides the following methods and attributes:

response.ok

Returns true if the request received a status in the OK range (200-299).

response.status

Contains the status code of the response, e.g. 404 for a not found resource, 200 for a success.

response.statusText

A message related to the status attribute, e.g. OK for a status 200.

response.clone()

Will return another Object with the same shape and content as response.

response.text(), response.json(), response.blob()

Will return the response content as plain text, JSON and Blob, respectively.

response.headers

Again, Unfetch doesn't implement a full spec-compliant Headers Class, emulating some of the Map-like functionality through its own functions:

  • headers.keys: Returns an Array containing the key for every header in the response.
  • headers.entries: Returns an Array containing the [key, value] pairs for every Header in the response.
  • headers.get(key): Returns the value associated with the given key.
  • headers.has(key): Returns a boolean asserting the existence of a value for the given key among the response headers.

Caveats

Adapted from the GitHub fetch polyfill readme.

The fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:

  • By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session.
fetch('/users', {
  credentials: 'include'
});
  • The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure or if anything prevented the request from completing.

    To have fetch Promise reject on HTTP error statuses, i.e. on any non-2xx status, define a custom response handler:

fetch('/users')
  .then(response => {
    if (response.ok) {
      return response;
    }
    // convert non-2xx HTTP responses into errors:
    const error = new Error(response.statusText);
    error.response = response;
    return Promise.reject(error);
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

Contribute

First off, thanks for taking the time to contribute! Now, take a moment to be sure your contributions make sense to everyone else.

Reporting Issues

Found a problem? Want a new feature? First of all see if your issue or idea has already been reported. If it hasn't, just open a new clear and descriptive issue.

Submitting pull requests

Pull requests are the greatest contributions, so be sure they are focused in scope, and do avoid unrelated commits.

๐Ÿ’ Remember: size is the #1 priority.

Every byte counts! PR's can't be merged if they increase the output size much.

  • Fork it!
  • Clone your fork: git clone https://github.com/<your-username>/unfetch
  • Navigate to the newly cloned directory: cd unfetch
  • Create a new branch for the new feature: git checkout -b my-new-feature
  • Install the tools necessary for development: npm install
  • Make your changes.
  • npm run build to verify your change doesn't increase output size.
  • npm test to make sure your change doesn't break anything.
  • Commit your changes: git commit -am 'Add some feature'
  • Push to the branch: git push origin my-new-feature
  • Submit a pull request with full remarks documenting your changes.

License

MIT License ยฉ Jason Miller

unfetch's People

Contributors

0x80 avatar andarist avatar balloob avatar danielruf avatar deptno avatar developit avatar dimpiax avatar ericmurphyxyz avatar iamakulov avatar jhnns avatar joaolucasl avatar johnlunney avatar khusa avatar kyleshevlin avatar misund avatar niedzielski avatar nikoladev avatar onagurna avatar patrickhulce avatar remko avatar resir014 avatar rishikeshdarandale avatar sakit0 avatar schonert avatar simon04 avatar stephenmathieson avatar styfle avatar sunsean avatar timneutkens avatar webreflection avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unfetch's Issues

TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation

export const sendSuggestion = ((data: any): Promise<any> => {
  console.log(JSON.stringify(data));
const apiUrl = `/api/suggest/`;
return fetch(apiUrl, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(data)
}).then(checkStatus)
    .then(r => r.json())
    .then(data => {
        console.log(data);
    });
});

const checkStatus = ((response: any) => {
  if (response.ok) {
    return response;
  } else {
    var error = new Error(response.statusText);
    console.log(error);
  //return Promise.reject(error);
  }
})

The script crashed with error
TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
After webkack it is looks:


exports.sendSuggestion = function (data) {
    var apiUrl = "/api/suggest/";
    return unfetch_1.default(apiUrl, {             //Code crashed here
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then(checkStatus).then(function (r) {
        return r.json();
    }).then(function (data) {
        console.log(data);
    });
};
var checkStatus = function checkStatus(response) {
    if (response.ok) {
        return response;
    } else {
        var error = new Error(response.statusText);
        console.log(error);
    }
};

import "unfetch/polyfill" does not work

I see the polyfill code here on github, but it doesn't seem to be in npm. I get this sort of thing:

Error: Cannot find module 'unfetch/polyfill' from '...'

Arrow function breaks IE compatibility

The following arrow function breaks compatibility with IE8+:

return new Promise( (resolve, reject) => {

I don't know if this is something you are willing to fix, if not the following should probably be removed from the README:

Supported: supports IE8+ (assuming Promise is polyfilled of course!)

Fail to handle header with blank value

The regex at line 28 does not handle header with a blank value.

Here is my test of the regex

var headers = "Server: \r\nmy-header: my-value\r\n";
headers.replace(/^(.?):\s([\s\S]*?)$/gm, (m, key, value) => {
console.log(key + ' | ' + value);
})

Expecting
"Server | "
"my-header | my-value"
Actual
"Server | my-header: my-value"

Missing API in README

// Beginner friendly

API section is missing in the README. This should either link to an external page like this or get documented.

Run GitHub/fetch tests against this polyfill

I did try putting together a PR that runs all tests at github/fetch but got overwhelmed by amount of work required. Basically it should be done via Git submodules and a shell/node script that swaps the implementation in the submodule with dist of this project.

Doing most of things manually I saw a few tests failing.

window not defined in web workers

The problem seems to be in browsers.js:

module.exports = window.fetch || (window.fetch = require('unfetch').default || require('unfetch'));

And I think this could be solved by replacing window with global?

Support ponyfilled Promise

Thanks for the great work on this library. I work on a tag management system that pushes code out to customers' websites. We avoid setting globals so that there are no unintended consequences on their websites and, in order to do so, we use a promise ponyfill within our library. We'd like to start using Unfetch, but it assumes that the promise will be set as a global, which for our case can't be the case when we need to use our ponyfill. We're willing to modify Unfetch for our needs to allow us to specify the promise implementation it should use, but I could see this being useful for other Unfetch consumers as well. Would there be any interest in adding support for this?

allow ponyfill promise

Would be nice to be able to provide Promise for environments where we don't want to modify the window.

Would you be open to such a PR?

possible implementation

export function createFetch(Promise) {
   return function(url, options) {
      // XMLHttpRequest stuff here
  }
}

export default typeof fetch=='function' ? fetch : createFetch(Promise)

usage

import Promise from 'es6-promise'
import { createFetch } from 'unfetch'

const fetch = createFetch(Promise)

How to hide console.error

I'm using isomorphic-unfetch with next.js
By the way, there is some 400 console.error on console in production.
try, catch not worked.
I have tried to find way to hide them on google but fail to get answer.
In production, I don't want to reveal my API server address in console.
Is there any way to hide them?

jsnext:main / module build

At the moment jsnext:main respectively module points to src/index.js. This leads to the situation where the consuming package / application needs to transpile unfetch as well in their build because older browsers don't understand arrow functions and so on.

jsnext:main or module code should always already be transpiled. The only difference is that they use ES6 module syntax instead of commonjs function calls.

See also webpack/webpack#2902 (comment) and pkg.module in rollup โ˜บ๏ธ

Convert fully to es6?

Seeing as this is already using es6, we can use destructuring and defaults to get even more byte savings. Would you accept a PR that does so?

Publish isomorphic-unfetch with types

It seems the latest version of isomorphic-unfetch on npm does not yet have the recently added typescript definition. Would it be possible to publish a new release that includes this update or are there blockers that we can help resolve?

xml() method is invented

Looks like I picked up baggage in my understanding of Fetch and invented an .xml() method on Response that doesn't actually exist. We'll need to remove that since it's not spec compliant.

Originally noted here: tkh44/holen#3

packages/isomorphic-unfetch/index.d.ts - Exports and export assignments are not permitted in module augmentations.

When trying to compile using Typescript, I got the following error:

node_modules/isomorphic-unfetch/index.d.ts:18:3 - error TS2666: Exports and export assignments are not permitted in module augmentations.

18   export = unfetch;
     ~~~~~~

I don't really understand what's happening but I managed to work around it by manually deleting line 18.

In case its helpful to anybody, steps to reproduce:
Typescript Version 2.9.2

cd node_modules/isomorphic-unfetch
echo "{}" > tsconfig.json
tsc

Function Expected IE11 Error

In the client side when a request is executed in IE11 I got Function Expected in this return statement:

typeof process=='undefined' ? (require('unfetch').default || require('unfetch')) : (function(url, opts) { return require('node-fetch')(url.replace(/^\/\//g,'https://'), opts); })

I'm using apollo client to make a graphql request, that this depends on a polyfill like isomorphic-unfetch

Issue with Safari Mobile on iOS 9

I'm using preact-cli default set up and unfetch doesn't work there.
Device: iPhone 5S
Safari user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_2_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13D15 Safari/601.1

I hope I can give more details but I'm using Ubuntu laptop and debugging it via ios-webkit-debug-proxy so I have no access to console.log (or whatever).

Switch to isomorphic-fetch and it works again

global default options and handlers

Since fetch apis are used a lot in a typical web application, it would be nice to have a unfetch.defaults object that sets default parameters of all requests.
A use case would be to set base URL of all requests.

unfetch.defaults.baseURL = 'my-api-endpoint'

NPM Types not working

when using import fetch from 'unfetch' types are not found. It seems the types are not included in the npm package ?

Works unfetch with php $_POST?

During tests with native fetch() the php $_POST wasn't populated. I can get it with php://input but loose some CMF features :(

Will unfetch work with php $_GET / $_POST?

Maybe we don't need fetch

/*
 * usage
 * 
 * componentDidMount() {
 *  unfetch('www.example.com/api/',
 *    {method: 'post', body: JSON.stringify({data: 123})},
 *    c => this.xhr = c
 *  )
 * }
 * componentWillUnmount() {
 *   this.xhr && this.xhr.abort() // this.xhr.onprogress = xx is also ok...
 * }
 * 
*/
function unfetch(url, options, cb) {
	options = options || {};
	return new Promise( (resolve, reject) => {
		let request = new XMLHttpRequest();
		request.open(options.method || 'get', url);

		for (let i in options.headers) {
			request.setRequestHeader(i, options.headers[i]);
		}

		request.withCredentials = options.credentials=='include';

		request.onload = () => {
			resolve(response());
		};

		request.onerror = reject;

		request.send(options.body);
		typeof cb === 'function' && cb(request);
		function response() {
			let keys = [],
				all = [],
				headers = {},
				header;

			request.getAllResponseHeaders().replace(/^(.*?):\s*([\s\S]*?)$/gm, (m, key, value) => {
				keys.push(key = key.toLowerCase());
				all.push([key, value]);
				header = headers[key];
				headers[key] = header ? `${header},${value}` : value;
			});

			return {
				ok: (request.status/100|0) == 2,		// 200-299
				status: request.status,
				statusText: request.statusText,
				url: request.responseURL,
				clone: response,
				text: () => Promise.resolve(request.responseText),
				json: () => Promise.resolve(request.responseText).then(JSON.parse),
				blob: () => Promise.resolve(new Blob([request.response])),
				headers: {
					keys: () => keys,
					entries: () => all,
					get: n => headers[n.toLowerCase()],
					has: n => n.toLowerCase() in headers
				}
			};
		}
	});
}

Reference to the SourceMap in dist

The JS files in the dist contain a comment that references the SourceMap. When you import it and use something Webpack, there will not be the source map at the URL provided in the comment leading to a 404. Would it make sense to remove that line?

Thanks for the excellent package โค๏ธ

Typescript issue: weird dependency on node-fetch in declaration file

First of all thanks for awesome polyfill @developit. It's brilliant and altogether with preact it makes a perfect match for our product bundle!

As for this issue I'm not sure why there's a dependency on node-fetch in declaration file. When I try to use unfetch in my TS code I get this:

ERROR in [at-loader] ./node_modules/unfetch/src/index.d.ts:6:8 
        TS7016: Could not find a declaration file for module 'node-fetch'. '/Users/dsorin/.../node_modules/node-fetch/index.js' implicitly has an 'any' type.
      Try `npm install @types/node-fetch` if it exists or add a new declaration (.d.ts) file containing `declare module 'node-fetch';`

I know this can be fixed by installing typings for node-fetch but this leads to a further questions like "what's this typing doing in our dependencies if we don't use node-fetch package? let's remove it".

Rationale behind the headers regex

Just reading through the source and saw the regex. Was wondering if someone could explain the rationale behind it.

For reference, it is (currently) /^(.*?):\s*([\s\S]*?)$/gm.

  • /^(.*?):\s* seems fine
  • [\s\S] is weird. \s is 'any of \r, \n, \t, \f, \v, '. \S is 'any character that isn't \s'. As far as I can tell, [\s\S] is the same as ..
  • *? is weird. We're matching to the end of the line. The fewest matches it can take is the same as the largest number. In the scenario it's used in, it's functionally equivalent to *, as there can be no more than one end-of-line per line.

I think that the regex could be changed to /^(.*?):\s*(.*)$/gm with no functional differences, and a few bytes saved.

Let me know if I've missed anything ๐Ÿ˜„ .

Edit: Ahh, looks like there is already a PR open that addresses this and some others.

Regex tests

Need to add regex tests.
Tested expression on validators, it gives strange results.
@developit could you provide expectations?

Missing some globals

The isomorphic-fetch library also polyfills the window.Response and window.Request constructors. Could unfetch support those instead of generating a response function inline?

The use case on our end is we extend the .json() method to first strip off an anti-XSS string.

Empty isomorphic-unfetch package

I tried to write a unit test for my Browser application that does not run in the Browser but in my Bash with ava or tape. I'm using unfetch as a ponyfill by the way.

So my tests are crashing because it cannot find XMLHttpRequest. I looked at your source code here and found out that there is a isomorphic-unfetch. Great! So I can import isomorphic-unfetch in my app and it should run in the Browser and in my tests that run in a NodeJS environment.

Unfortunately the package on npm is empty.

untitled

Ponyfill acts as a polyfill

Why is this advertised as a ponyfill, when the export line looks for an existing fetch function to bind to? This renders any native implementations non-native, and breaks any libraries looking for that as a marker for feature detection.

export default typeof fetch=='function' ? fetch.bind() : function(url, options) {

Using this breaks PouchDB on Safari.

pouchdb/pouchdb#7085

not compatible with UglifyJs?

After adding this to my app I get the following error when building for production:

ERROR in js/main.js from UglifyJs
Invalid assignment [js/main.js:11866,39]

Using webpack 4.19.1 and uglifyjs-webpack-plugin 2.0.1

Any ideas what this could be?

Webpack error

When deploying on Zeit Now v2 , there is an error from webpack, that I found is due to this package

ModuleDependencyWarning: Critical dependency: the request of a dependency is an expression
                              at Compilation.reportDependencyErrorsAndWarnings (/tmp/2b34e4f6/node_modules/webpack/lib/Compilation.js:1359:23)
                              at Compilation.finish (/tmp/2b34e4f6/node_modules/webpack/lib/Compilation.js:1165:9)
                              at hooks.make.callAsync.err (/tmp/2b34e4f6/node_modules/webpack/lib/Compiler.js:544:17)
                              at _err0 (eval at create (/tmp/2b34e4f6/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:11:1)
                              at Promise.all.then (/tmp/2b34e4f6/node_modules/webpack/lib/DynamicEntryPlugin.js:74:20)
                              at <anonymous>
                              at process._tickCallback (internal/process/next_tick.js:188:7)
                              at CommonJsRequireContextDependency.getWarnings (/tmp/2b34e4f6/node_modules/webpack/lib/dependencies/ContextDependency.js:40:18)
                              at Compilation.reportDependencyErrorsAndWarnings (/tmp/2b34e4f6/node_modules/webpack/lib/Compilation.js:1354:24)
                              at Compilation.finish (/tmp/2b34e4f6/node_modules/webpack/lib/Compilation.js:1165:9)
                              at hooks.make.callAsync.err (/tmp/2b34e4f6/node_modules/webpack/lib/Compiler.js:544:17)
                              at _err0 (eval at create (/tmp/2b34e4f6/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:11:1)
                              at Promise.all.then (/tmp/2b34e4f6/node_modules/webpack/lib/DynamicEntryPlugin.js:74:20)
                              at <anonymous>
                              at process._tickCallback (internal/process/next_tick.js:188:7)

XDomainRequest. IE 8 will not work when CORS requests

steps to reproduce

[email protected]:

<!-- page1.html -->
<body>
  <script src="https://unpkg.com/[email protected]/polyfill/index.js"></script>
  <script src="https://unpkg.com/[email protected]/promise.min.js"></script>
  <script>
    fetch('page2.html')
        .then(function(response) {
            return response.text();
        })
        .then(function(data) {
            console.log(data);
        });
  </script>
    
<!-- page2.html -->
... any data ...

use any http server that supports Access-Control-Allow-Origin headers:

npm install http-server -g
http-server -p 8081 --cors
  • --cors - to enable CORS via the Access-Control-Allow-Origin

result

Through VM WinXP SP3 with IE version: 8.0.6001.18702 Update version: 0

  • F12 - Document Mode = 8 and 7.

and/or

  • Win10 IE11 - F12 - Emulation - Document Mode = 7 and 8 / User agent: 7/8

It does not work at all!

user-space solutions

Here's my example of hack for already released unfetch version like 4.0.1. Works fine for IE7+:

var send = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function()
{
    this.onreadystatechange = function()
    {
        // TODO: prevent duplicate calling of onload if it's not CORS!
        if(this.readyState === 4 && this.status === 200) {
            return this.onload.apply(this, arguments);
        }
    }
    return send.apply(this, arguments);
}
 
// IE7+ ok now

Actually, even IE 11 with 5+ emulation, that of course strange :) because it should be ActiveXObject before IE7. Bad emulation :)

However, for real IE8 CORS support we should have requests through XDomainRequest not for XMLHttpRequest. Thus, your onload() is silent.

add support for aborting via AbortController

https://developers.google.com/web/updates/2017/09/abortable-fetch

Currently it is only implemented in Firefox 57 and is coming to other browsers soon.

const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 5000);

fetch(url, { signal }).then(response => {
  return response.text();
}).then(text => {
  console.log(text);
});

Will most likely need to implement another npm package that just include AbortController package. I found one but it also pollyfills fetch. https://github.com/mo/abortcontroller-polyfill

unfetch/polyfill doesnโ€™t work in webpack 2

When I do:

import 'unfetch/polyfill';

I see this error in Safari 10:

TypeError: fetch is not a function.

Because fetchย is actually a ES module wrapper:

{__esModule: true, default: function}

I suppose itโ€™s because you have require('.') in polyfll.js and webpack 2 resolves it to index.es.js. So this code works for me:

if (!window.fetch) {
    window.fetch = require('unfetch').default;
}

Iโ€™d be happy to submit a PR but not sure what would be the right fix for this.

Is the typescript definition exported correctly?

I'm having trouble with unfetch >= 3.1.1. The new TypeScript definition actually broke our build, and I'm not sure how to fix it.

The change was made in PR #89, in which the default export was removed from src/index.d.ts. Was this intentional? The PR is named "Fix isomorphic-unfetch definition" but packages/isomorphic-unfetch/index.d.ts is not changed, instead src/index.d.ts was changed.

Since src/index.mjs export default, shouldn't src/index.d.ts also export default?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.