如何为浏览器兼容性编译 Fetch API 和 promises?

How to compile Fetch API and promises for browser compatibility?

我很好奇当您想使用 fetch() 和 promises 并让它 compiled/poly-filled 获得最佳浏览器支持时,最好的解决方案是什么。

当我尝试在 babeljs.io 上编译 fetch/promise 代码时,我没有看到编译版本,所以这让我对如何使用 fetch 和 promises 而不是 XML 并且有良好的浏览器支持?

提前感谢您对我如何实现这一目标的任何建议。

下面是我从 babel 编译器得到的结果,正如你所看到的,除了将 const 更改为 var 之外,结果并不是我所期望的!

const image = document.querySelector('.my-image');
fetch('flowers.jpg').then(function(response) {
return response.blob();
}).then(function(blob) {
const objectURL = URL.createObjectURL(blob);
image.src = objectURL;
}); 

VS

var image = document.querySelector('.my-image');
fetch('flowers.jpg').then(function(response) {
return response.blob();
}).then(function(blob) {
var objectURL = URL.createObjectURL(blob);
image.src = objectURL;
});

Babel 处理(主要)语法翻译,例如将 const(和 let)转换为合适的 var 声明。虽然它确实通过 @babel/polyfill 提供了 polyfill,但 fetch 不是其中之一。

有很多 fetch polyfill,假设您的项目是基于浏览器的,例如 here. To include it in your project you can either download the .umd.js package and include it in a <script> tag, or use a bundler such as webpack, browserify or rollup 将其构建到您的项目中。