45

GitHub - sindresorhus/ky-universal: Use Ky in both Node.js and browsers

 5 years ago
source link: https://github.com/sindresorhus/ky-universal
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

readme.md

ky-universal Build Status

Use Ky in both Node.js and browsers

Ky is made for browsers, but this package makes it possible to use it in Node.js too, by polyfilling most of the required browser APIs using node-fetch and abort-controller.

This package can be useful for:

  • Isomorphic code
  • Web apps (React, Vue.js, etc.) that use server-side rendering (SSR)
  • Testing browser libraries using a Node.js test runner

Note: Before opening an issue, make sure it's an issue with Ky and not its polyfills. Generally, if something works in the browser, but not in Node.js, it's an issue with node-fetch or abort-controller.

Keep in mind that Ky targets modern browsers when used in the browser. For older browsers, you will need to transpile and use a fetch polyfill.

If you only target Node.js, I would strongly recommend using Got instead.

Install

$ npm install ky ky-universal

Note that you also need to install ky.

68747470733a2f2f63352e70617472656f6e2e636f6d2f65787465726e616c2f6c6f676f2f6265636f6d655f615f706174726f6e5f627574746f6e4032782e706e67

Usage

Use it like you would use Ky:

const ky = require('ky-universal');

(async () => {
	const parsed = await ky('https://httpbin.org/json').json();

	//
})();

FAQ

How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?

Use it like you would use Ky:

import ky from 'ky-universal';

(async () => {
	const parsed = await ky('https://httpbin.org/json').json();

	//
})();

Webpack will ensure the polyfills are only included and used when the app is rendered on the server-side.

How do I test a browser library that uses Ky in AVA?

Put the following in package.json:

{
	"ava": {
		"require": [
			"ky-universal"
		]
	}
}

The library that uses Ky will now just work in AVA tests.

Related

  • ky - Tiny and elegant HTTP client based on the browser Fetch API
  • got - Simplified HTTP requests in Node.js

License

MIT © Sindre Sorhus


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK