修改index.js,并且直接使用babel去处理
const sum = (a, b) => a + b
Promise.resolve(100).then(data => data);
[10, 20, 30].includes(20)
npx babel ./index.js
# 结果如下
"use strict";
var sum = function sum(a, b) {
return a + b;
};
Promise.resolve(100).then(function (data) {
return data;
});
[10, 20, 30].includes(20);
# babel本身只解析语法,新的API是不会解析的
正是因为babel本身不能解析这个API,为了兼容非最新浏览器,就得使用babel-polyfill
使用babel-polyfill
package.json
{
"name": "babel",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.12.1",
"@babel/core": "^7.12.3",
"@babel/preset-env": "^7.12.1"
},
"dependencies": {
"@babel/polyfill": "^7.12.1"
}
}
index.js
import '@babel/polyfill'
const sum = (a, b) => a + b
Promise.resolve(100).then(data => data);
[10, 20, 30].includes(20)
npx babel index.js
# babel只检查语法且不处理模块化,webpack去处理模块化
# 以下是结果
require("@babel/polyfill");
var sum = function sum(a, b) {
return a + b;
};
Promise.resolve(100).then(function (data) {
return data;
});
[10, 20, 30].includes(20);
配置按需引入 babel-polyfill
修改babelrc文件
{
"presets": [
[
"@babel/preset-env",
// 增加以下内容
{
"useBuiltIns": "usage",
"corejs": 3
}
]
],
"plugins": []
}
修改index.js,删掉全部引入的语句
const sum = (a, b) => a + b
Promise.resolve(100).then(data => data);
[10, 20, 30].includes(20)
npx babel idnex.js
# 以下是结果
"use strict";
require("core-js/modules/es.array.includes");
require("core-js/modules/es.object.to-string");
require("core-js/modules/es.promise");
var sum = function sum(a, b) {
return a + b;
};
Promise.resolve(100).then(function (data) {
return data;
});
可见,已经做到了按需引入