Let's learn another good trick which may help you develop isomorphic components. Say that we need to have an HTTP client utility that will be used to request data from the server. The implementation of this utility will differ based on what environment it's targeting. In Node.js, it will use native http
module, and on the client, it will use the browser's XMLHttpRequest
. Or, if we want to work with a higher level of abstraction, we can use the node-fetch
module on the server and the whatwg-fetch
module on the client.
You can install these two npm modules by running the following:
npm install whatwg-fetch node-fetch --save
The first one uses XHTMLHttpRequest
behind the scene and the later one-Node.js http
module, both providing almost the same API.
Now, create two files, one for each of the environments we're targeting:
// core/fetch/fetch.client.js import 'whatwg-fetch'; export default self.fetch.bind(self); exportconst Headers = self.Headers; exportconst Request...