diff --git a/fetch.js b/fetch.js index f2f466d7..98b1f2be 100644 --- a/fetch.js +++ b/fetch.js @@ -1,14 +1,20 @@ -(function(self) { +(function(root, factory) { + /* jshint strict:false */ + /* globals define, module */ + if (typeof define === 'function' && define.amd) { + define([], function() { return factory({}, root) }) + } else if (typeof module === 'object' && module.exports) { + factory(module.exports, root) + } else { + root.WHATWGFetch = factory({}, root) + } +})(typeof self !== 'undefined' ? self : this, function(exports, global) { 'use strict'; - if (self.fetch) { - return - } - var support = { - searchParams: 'URLSearchParams' in self, - iterable: 'Symbol' in self && 'iterator' in Symbol, - blob: 'FileReader' in self && 'Blob' in self && (function() { + searchParams: 'URLSearchParams' in global, + iterable: 'Symbol' in global && 'iterator' in Symbol, + blob: 'FileReader' in global && 'Blob' in global && (function() { try { new Blob() return true @@ -16,8 +22,8 @@ return false } })(), - formData: 'FormData' in self, - arrayBuffer: 'ArrayBuffer' in self + formData: 'FormData' in global, + arrayBuffer: 'ArrayBuffer' in global } if (support.arrayBuffer) { @@ -415,11 +421,11 @@ return new Response(null, {status: status, headers: {location: url}}) } - self.Headers = Headers - self.Request = Request - self.Response = Response + exports.Headers = Headers + exports.Request = Request + exports.Response = Response - self.fetch = function(input, init) { + exports.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request = new Request(input, init) var xhr = new XMLHttpRequest() @@ -462,5 +468,14 @@ xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) }) } - self.fetch.polyfill = true -})(typeof self !== 'undefined' ? self : this); + exports.fetch.polyfill = true + + if (!global.fetch) { + global.fetch = exports.fetch + global.Headers = Headers + global.Request = Request + global.Response = Response + } + + return exports +}); diff --git a/script/test b/script/test index bc471d43..0fd46821 100755 --- a/script/test +++ b/script/test @@ -7,3 +7,5 @@ if [ -n "$SAUCE_BROWSER" ]; then else ./script/phantomjs fi + +./node_modules/mocha/bin/mocha test/cjs.js diff --git a/test/cjs.js b/test/cjs.js new file mode 100644 index 00000000..4d53cf34 --- /dev/null +++ b/test/cjs.js @@ -0,0 +1,13 @@ +/* global describe, it, require */ + +var isFunction = require('chai').assert.isFunction +var WHATWGFetch = require('../') + +describe('Common JS exports', function() { + it('should provide all the CJS exports', function() { + isFunction(WHATWGFetch.fetch) + isFunction(WHATWGFetch.Headers) + isFunction(WHATWGFetch.Request) + isFunction(WHATWGFetch.Response) + }) +})