过去我们使用 babel 对 js 代码进行了兼容性处理,其中使用@babel/preset-env 智能预设来处理兼容性问题。
它能将 ES6 的一些语法进行编译转换,比如箭头函数、点点点运算符等。但是如果是 async 函数、promise 对象、数组的一些方法(includes)等,它没办法处理。
所以此时我们 js 代码仍然存在兼容性问题,一旦遇到低版本浏览器会直接报错。所以我们想要将 js 兼容性问题彻底解决。
做一个具有兼容性的语法使用promise
const promise = Promise.resolve();
promise.then(() => {
console.log("hello promise");
});
![](https://i-blog.csdnimg.cn/blog_migrate/893d809000e875e58f1ba2e0a1255d08.png)
重新打包
> npm run build
观察打包后的文件
Promise语法完全输出,是ES6语法,会报错,在IE8以下浏览器会报错
![](https://i-blog.csdnimg.cn/blog_migrate/de2c6bfe320256be0558241bd9834ed9.png)
发现有个小问题,输出文件hash太长了contenthash+8
filename: "static/js/[name].[contenthash:8].js",
所以使用core-js 是专门用来做 ES6 以及以上 API 的 polyfill(补丁)。使用社区上提供的一段代码,让我们在不兼容某些新特性的浏览器上,使用该新特性。
法一:直接引入全部
安装包
npm i core-js
import "core-js";
在main.js中引入
![](https://i-blog.csdnimg.cn/blog_migrate/1dd77567f3291e6efe9f7d5e5552c77c.png)
map是动态导入生成的文件,runtime是依赖关系,486是新的文件,将corejs单独打包、
main里面是promise还是。
![](https://i-blog.csdnimg.cn/blog_migrate/a10df7988ad811009aae3320ef4b9653.png)
core里面对promise做了解释
![](https://i-blog.csdnimg.cn/blog_migrate/5da5f3a6fd66f1f8ded5fe5f9c685eab.png)
问题:这样引入会将所有兼容性代码全部引入,体积太大了。我们只想引入 promise 的 polyfill补丁。
法二:手动按需引入
import "core-js/es/promise";
![](https://i-blog.csdnimg.cn/blog_migrate/028e4dc1129c5f156f500863a489c7de.png)
![](https://i-blog.csdnimg.cn/blog_migrate/fd0613fadba5163b3b71b9fdc7d1adde.png)
![](https://i-blog.csdnimg.cn/blog_migrate/709d87540dc2721433bcfdfad1bffc00.png)
缺点:只引入打包 promise 的 polyfill,打包体积更小。但是将来如果还想使用其他语法,我需要手动引入库很麻烦
法二:自动按需引入
使用智能预设 babel.config.js
https://www.babeljs.cn/docs/babel-preset-env#corejs
useBuiltIns:按需加载
将main.js引入不同的es语法查看适配性
![](https://i-blog.csdnimg.cn/blog_migrate/e44d19668808834a914f44a8c2587f62.png)
在babel.config.js写
module.exports = {
// 智能预设:能够编译ES6语法
presets: [
[
"@babel/preset-env",
// 按需加载core-js的polyfill
{ useBuiltIns: "usage", corejs: { version: "3", proposals: true } },
],
],
};
发现没有效果解决办法使用targets
法一:
module.exports = {
// 智能预设:能够编译ES6语法
presets:
[
[
"@babel/preset-env",
// 按需加载core-js的polyfill
{
targets: {
chrome: '78', firefox: '60', ie: '11', safari: '17', edge: '17'
},
useBuiltIns: "usage",
corejs: { version: "3", proposals: true }
},
],
]
};
法二
module.exports = {
// 智能预设:能够编译ES6语法
presets:
[
[
"@babel/preset-env",
// 按需加载core-js的polyfill
{
// targets: {
// chrome: '78', firefox: '60', ie: '11', safari: '17', edge: '17'
// },
"targets": {
"browsers": ["last 2 versions", "ie 11"]
},
useBuiltIns: "usage",
corejs: { version: "3", proposals: true }
},
],
]
};
npm run build
重新加载
![](https://i-blog.csdnimg.cn/blog_migrate/d46718519318d0156421ad0c2b907084.png)
![](https://i-blog.csdnimg.cn/blog_migrate/bfbf7c8fa008ccf2fb5824048d951dcc.png)