I am making a global library which can be used in any environment (node,browser,es6 modules). For that I am generating a UMD file using Webpack. But how do I handle functions that contradict the opposite environments (Like fetch requests). I started using axios as I found that it works for both browser and node, but faced different problems which I am going to state below.
Directly using Axios in my library: Node gave error that "XMLHttpRequest is not defined".
Specifying "Axios" as Externals in Webpack:: The library starts working fine in Node but now it stops working in Browser. Because Axios is undefined in browser now.
Special Case: I also provide ES6 support for the library by adding module entry in package.json which point to src/index.js. Now, in browser it becomes issue because I am using import axios from 'axios' in my Library file. And since the browser takes it as it is in case of ES6 module (I am talking about when we use <script type='module'>import {func} from "./myLibrary.js" .....</script> ). It becomes an issue because the browser don't work with absolute paths, it requires relative paths. So, is it not possible to make such kind of ES6 support for Browsers? Accessing the same ES6 library in React works fine, because of course it works on top of module bundler and it don't have the same issue as browser(script tag).
So the point is, the more I search on it and try to fix the issues, I am getting more and more issues. Is there any standard way to go about it? Because if there exist something as a UMD file Format, it should be possible to make global libraries. I have only talked about Axios/Fetch in this situtation but I am not sure what other kind of issues might I face as well in other situations.
fetch or XMLHttpRequest are functions that belongs to window browser object. So nodejs cannot have them, node has not a window object. You have to include some module to access the fetch-like API that provides browser.