修改index.js,并且直接使用babel去处理

  1. const sum = (a, b) => a + b
  2. Promise.resolve(100).then(data => data);
  3. [10, 20, 30].includes(20)
  1. npx babel ./index.js
  2. # 结果如下
  3. "use strict";
  4. var sum = function sum(a, b) {
  5. return a + b;
  6. };
  7. Promise.resolve(100).then(function (data) {
  8. return data;
  9. });
  10. [10, 20, 30].includes(20);
  11. # babel本身只解析语法,新的API是不会解析的

正是因为babel本身不能解析这个API,为了兼容非最新浏览器,就得使用babel-polyfill

使用babel-polyfill

package.json

  1. {
  2. "name": "babel",
  3. "version": "1.0.0",
  4. "main": "index.js",
  5. "license": "MIT",
  6. "devDependencies": {
  7. "@babel/cli": "^7.12.1",
  8. "@babel/core": "^7.12.3",
  9. "@babel/preset-env": "^7.12.1"
  10. },
  11. "dependencies": {
  12. "@babel/polyfill": "^7.12.1"
  13. }
  14. }

index.js

  1. import '@babel/polyfill'
  2. const sum = (a, b) => a + b
  3. Promise.resolve(100).then(data => data);
  4. [10, 20, 30].includes(20)
  1. npx babel index.js
  2. # babel只检查语法且不处理模块化,webpack去处理模块化
  3. # 以下是结果
  4. require("@babel/polyfill");
  5. var sum = function sum(a, b) {
  6. return a + b;
  7. };
  8. Promise.resolve(100).then(function (data) {
  9. return data;
  10. });
  11. [10, 20, 30].includes(20);

这就相当于引入了补丁,就可以在所有浏览器中使用了。

配置按需引入 babel-polyfill

修改babelrc文件

  1. {
  2. "presets": [
  3. [
  4. "@babel/preset-env",
  5. // 增加以下内容
  6. {
  7. "useBuiltIns": "usage",
  8. "corejs": 3
  9. }
  10. ]
  11. ],
  12. "plugins": []
  13. }

修改index.js,删掉全部引入的语句

  1. const sum = (a, b) => a + b
  2. Promise.resolve(100).then(data => data);
  3. [10, 20, 30].includes(20)
  1. npx babel idnex.js
  2. # 以下是结果
  3. "use strict";
  4. require("core-js/modules/es.array.includes");
  5. require("core-js/modules/es.object.to-string");
  6. require("core-js/modules/es.promise");
  7. var sum = function sum(a, b) {
  8. return a + b;
  9. };
  10. Promise.resolve(100).then(function (data) {
  11. return data;
  12. });

可见,已经做到了按需引入