我一直在尝试使用 Babel 和 shims/polyfills 使我的简单 HTML/JS 网站向后兼容(IE11 及以下),但一直无法正确执行此操作。我目前的网站使用了一些新的功能,如Promise()
,fetch()
,document.querySelectorAll().forEach()
,和() => {}
。
我尝试添加es6-shim、es5-shim、fetch- polyfill和promise- polyfill ,在通过 Babel 从 es6 -> es5 转译我的代码之上。无论如何,当我使用较旧的浏览器(例如 IE 11 或 10)加载我的网页时,我会收到多个错误。错误说这() => {}
不起作用,这.forEach()
不是一个函数,这没有意义,因为我使用的是垫片和 Babel。
这是我的 JS 包括的顺序:
[... body content ...]
<script src="assets/libs/es5-shim/es5-shim.min.js" type="text/javascript"></script>
<script src="assets/libs/es6-shim/es6-shim.min.js" type="text/javascript"></script>
<script src="assets/libs/promise-polyfill/promise-polyfill.min.js" type="text/javascript"></script>
<script src="assets/libs/fetch-polyfill/fetch.umd.js" type="text/javascript"></script>
[... rest of scripts ..]
并将我的 es6 代码转换为 es5,我执行了以下操作:
npm install -D babel-cli
npm install -D babel-preset-env
// .babelrc
{
"presets": ["env"]
}
// package.json
...
"scripts": {
"build": "babel src -d build",
},
...
npm run build
两个示例错误:“对象不支持 forEach 的属性或方法”( querySelectorAll().forEach()
) 和“语法错误”( () => {}
)
您使用的是旧版本的 Babel,切换到 Babel 7 并开始使用@babel/preset-env
. NodeList.forEach
不会在任何 IE 中工作,需要单独填充,因为 Babel polyfill 不会填充任何缺少的原型方法。
最短的 polyfill 可能是
if (!NodeList.prototype.forEach) NodeList.prototype.forEach = Array.prototype.forEach;
您还需要配置您.babelrc
的代码,以便为 IE 转换代码。Babel 7 的示例:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"browsers": ["ie >= 10", "last 1 version"]
}
}
]
]
}
PS:那时你可能不需要垫片。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句