babel是一个javascript编译器,它将ECMAscript2015以上的语法转换成旧版本浏览器可执行的代码。
//babel转码前
const arr = [1,2,3,4,5]
arr.map(item=>item+2)
//babel转码之后
const arr = [1,2,3,4,5]
arr.map(function(item){
return item+2;
})
上面将es6的箭头函数转换成了浏览器可识别执行的回调函数的方式。
使用babel编译器时,需要了解babel几大核心模块,包含集成包、工具包、预设presets、plugins插件、配置文件。
集成包和工具包是babel的底层核心插件。一般情况下使用预设presets、plugins插件、配置文件即可。接下来使用babel编译器将ES6转es5。
npm init -y
npm install --save-dev @babel/core @babel/cli @babel/preset-env
@babel/core babel官方提供的核心库。
@babel/cli Babel内置的 CLI,用来从命令行编译文件。
@babel/preset-env babel官方预设
|-node_modules
|-package.json
|-package-lock.json
在根目录下创建一个babel.config.json配置文件。并将安装的预设配置到babel中,如下:
{
"presets": [
["@babel/preset-env",{}]
],
"plugins": []
}
创建一个用于编译的js文件。
index.js
// 箭头函数
const fn = msg => {
console.log(msg)
}
fn('hello world')
// 拓展符号...
var arr1 = [1,2,3]
var arr2 = [4,5,6]
var arr = [...arr1,...arr2]
console.log(arr)
// 对象扩展符
const obj1 = {"a":1}
const obj2 = {"b":2,"a":3}
const obj = {...obj1 ,...obj2}
console.log(obj)
使用已安装的@babel/cli来编译index.js文件。两种编译命令。
//第一种npx babel
npx babel index.js -o index.babel.js
//第二种./node_modules/.bin/babel
./node_modules/.bin/babel index.js -o index.babel2.js
index.js的es6语法转换成了es5
"use strict";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// 箭头函数
var fn = function fn(msg) {
console.log(msg);
};
fn('hello world'); // 拓展符号...
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr = [].concat(arr1, arr2);
console.log(arr); // 对象扩展符
var obj1 = {
"a": 1
};
var obj2 = {
"b": 2,
"a": 3
};
var obj = _objectSpread(_objectSpread({}, obj1), obj2);
console.log(obj);
预设相当于一组babel插件的组合,不需要单独去配置多个插件。babel官方提供了几种常用的预设,基本能满足我们日常的所需。也可以自己配置预设。
@babel/preset-env
@babel/preset-react
@babel/preset-typescript
@babel/preset-flow
进入npmjs.com,搜索@babel有接近200babel插件。
babel插件列表:
TC39 Proposals
decorators
do-expressions
duplicated-named-capturing-groups-regex
export-default-from
export-namespace-from
function-bind
function-sent
partial-application
pipeline-operator
throw-expressions
record-and-tuple
ES2022
class-properties
class-static-block
private-property-in-object
syntax-top-level-await
ES2021
logical-assignment-operators
numeric-separator
ES2020
export-namespace-from
nullish-coalescing-operator
optional-chaining
syntax-dynamic-import
syntax-import-meta
syntax-bigint
ES2019
optional-catch-binding
json-strings
ES2018
async-generator-functions
dotall-regex
named-capturing-groups-regex
object-rest-spread
unicode-property-regex
ES2017
async-to-generator
ES2016
exponentiation-operator
ES2015
arrow-functions
block-scoped-functions
block-scoping
classes
computed-properties
destructuring
duplicate-keys
for-of
function-name
instanceof
literals
new-target
object-super
parameters
shorthand-properties
spread
sticky-regex
template-literals
typeof-symbol
unicode-escapes
unicode-regex
ES5
property-mutators
ES3
member-expression-literals
property-literals
reserved-words
Module Formats
modules-amd
modules-commonjs
modules-systemjs
modules-umd
React
react-constant-elements
react-inline-elements
React Preset
react-display-name
react-jsx
react-jsx-compat
react-jsx-self
react-jsx-source
Flow
flow-strip-types
TypeScript
typescript
Misc
external-helpers
jscript
object-assign
object-set-prototype-of-to-assign
proto-to-assign
regenerator
runtime
strict-mode
Syntax Only
syntax-bigint (ES2020)
syntax-dynamic-import (ES2020)
syntax-import-meta (ES2020)
syntax-top-level-await (ES2022)
提供几种配置文件
babel.config.json 或者 .babelrc
{
"plugins":[],
"presets":[]
}
babel.config.js 或者 .babelrc.js
const presets = [ ... ];
const plugins = [ ... ];
if (process.env["ENV"] === "prod") {
plugins.push(...);
}
module.exports = { presets, plugins };
package.json中配置babel
{
"name": "my-package",
"version": "1.0.0",
"babel": {
"presets": [ ... ],
"plugins": [ ... ],
}
}
es6转es5demo代码已上传到https://gitee.com/usuing/lession/tree/master/babel/
。欢迎star!