# Core-js (高版本 JS 语法补丁)

# 是什么

过去我们使用 babel 对 js 代码进行了兼容性处理,其中使用 @babel/preset-env 智能预设来处理兼容性问题。

它能将 ES6 的一些语法进行编译转换,比如箭头函数、扩展运算符等。

但是如果是 async 函数、promise 对象、数组的一些方法(includes)等,它没办法处理

所以此时我们 js 代码仍然存在兼容性问题,一旦遇到低版本浏览器会直接报错。

所以我们想要将 js 兼容性问题彻底解决 core-js 是专门用来做 ES6 以及以上 API 的 polyfill(polyfill 翻译过来叫做垫片/补丁)。

就是用社区上提供的一段代码,让我们在不兼容某些新特性的浏览器上,使用该新特性。

# 使用 Promise 异步语句

// main.js

// ...代码

// 添加promise代码
const promise = Promise.resolve();
promise.then(() => {
  console.log("hello promise");
});
1
2
3
4
5
6
7
8
9

直接使用会报错

ERROR in [eslint]
C:\webpack_practice\testDemo4\src\main.js
  59:17  error  'Promise' is not defined  no-undefined
1
2
3

# 安装

  • @babel/eslint-parser 是一个 npm 包,它是 Babel 和 ESLint 的一个插件,允许 ESLint 理解 Babel 编译的代码。
npm i @babel/eslint-parser -D
1
  • core-js:这是要安装的包的名称,core-js 是一个常用的 JavaScript 库,提供了对旧浏览器的兼容性支持,实现了一些新的 ECMAScript 特性。
npm i core-js
1

# 配置 .eslintrc.js 解释器


 




 




module.exports = {
  parser: "@babel/eslint-parser", // 支持最新的最终 ECMAScript 标准
  // ...其他配置
  // 环境配置
  env: {
    node: true, // 启用node中全局变量
    browser: true, // 启用浏览器中全局变量
    es6: true, // 启用除模块之外的所有 ECMAScript 6 功能
  },
};
1
2
3
4
5
6
7
8
9
10

必须开启 es6: true, 否则报错(注意这个报错是 Eslint 导致的语法检测错误,并非babel不能编译和兼容Promise)

ERROR in [eslint]
X\test\webpack_practice\testDemo4\src\main.js
  61:17  error  'Promise' is not defined  no-undef

✖ 1 problem (1 error, 0 warnings)
1
2
3
4
5

关于 开启 es6: true 的原因,查看eslint-指定解析器选项 (opens new window)

# 配置 babel.config.js 按需引入对应的语法补丁

module.exports = {
  // ...其他配置
  // 智能预设:能够编译ES6语法
  presets: [
    [
      "@babel/preset-env",
      // 按需加载core-js的polyfill
      { useBuiltIns: "usage", corejs: { version: "3", proposals: true } },
    ],
  ],
};
1
2
3
4
5
6
7
8
9
10
11
// 这是@babel/preset-env 预设的配置对象
{ useBuiltIns: "usage", corejs: { version: "3", proposals: true } }

// 这个选项告诉 Babel 按需加载 core-js 的 polyfill,而不是全部加载。
// 这样,只有当代码中实际使用了某个特性时,Babel 才会引入相应的 polyfill。
useBuiltIns: "usage";

// 这个对象进一步配置了 core-js 的行为。
// version: "3"指定了使用 core-js 的版本 3,
// proposals: true 表示启用对 Stage 3 ECMAScript 提案的 polyfill。
corejs: { version: "3", proposals: true }
1
2
3
4
5
6
7
8
9
10
11

完成后就可以在代码之中写高阶语法了,当前如果要搞事情,不嫌麻烦舍弃按需引入,使用手动引入的方式,具体看拓展

# 拓展: 手动引入 corejs-polyfill

不配置 babel.config.js 按需引入, 手动引入的步骤

/** 这样引入会将所有兼容性代码全部引入,体积大 */
// import "core-js";

/** import "core-js/es/promise"; 只引入打包 promise 的 polyfill,体积更小 */
import "core-js/es/promise";

// ...其他代码

// 添加promise代码
const promise = Promise.resolve();
promise.then(() => {
  console.log("hello promise");
});
~~~
1
2
3
4
5
6
7
8
9
10
11
12
13
14