【问题标题】:Babel doesn't convert fetch api codeBabel 不转换 fetch api 代码
【发布时间】:2018-08-24 14:41:38
【问题描述】:

fetch api 非常有用,但不幸的是它不适用于大多数浏览器,尤其是 Internet Explorer。我尝试使用 babel 将我的代码从 es6 转换为 es5,但它并没有解决这个问题。转为 es5 时仍然包含 fetch。我该如何解决这个问题。 这是 es6 代码:

var btnText = document.getElementById('btnText');
var btnJson = document.getElementById('btnJson');
btnText.addEventListener("click",fetchBtnText);
function fetchBtnText() {
  fetch("sample.txt")
    .then((response) => response.text())
.then((data) => console.log(data))
}

这里是到 es5 的转换

'use strict';
var btnText = document.getElementById('btnText');
var btnJson = document.getElementById('btnJson');
btnText.addEventListener("click", fetchBtnText);
function fetchBtnText() {
  fetch("sample.txt").then(function (response) {
    return response.text();
  }).then(function (data) {
    return console.log(data);
  });
}

【问题讨论】:

    标签: javascript html es6-promise fetch-api


    【解决方案1】:

    你可以像这样使用 polyfill https://github.com/github/fetch

    【讨论】:

    • 你能解释一下为什么它不能转换吗?
    • @StukedCoder Babel 是mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments,正如他们的home page 所述,Fetch API 不是 ECMAScript/javascript 语言规范的一部分,而是 Web API 的一部分。有关详细信息,请参阅here
    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 2018-08-08
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多