Babel简介

Babel简介

国内站点:https://www.babeljs.cn/
官方站点:https://babeljs.io/

插件是小型的 JavaScript 程序,用于指导 Babel 如何对代码进行转换
预设即一组预先设定的插件

@babel/core
@babel/cli
@babel/preset-env
@babel/polyfill

安装使用

创建babel-demo目录,并在该目录下创建package.json文件

mkdir babel-demo && cd babel-demo
npm init -y

安装babel的软件包

npm install @babel/core @babel/cli @babel/preset-env --save-dev

在项目的根目录下创建app.js文件,文件内容如下:

const colors = ['red', 'green', 'blue']

colors.forEach(color => {
    console.log(color)
})

const [firstColor, secondColor] = colors

安装转换箭头函数的插件,然后使用该插件转换app.js文件中的代码:

npm install @babel/plugin-transform-arrow-functions --save-dev
npx babel --plugins @babel/plugin-transform-arrow-functions app.js

由于我们只提供了转换箭头函数的插件,因此本次只转换箭头函数,转换之后的内容会被输出到控制台:

const colors = ['red', 'green', 'blue'];
colors.forEach(color => {
  console.log(color);
});
const [firstColor, secondColor] = colors;

使用预设提供的插件转换app.js,

npx babel --presets @babel/preset-env app.js

由于预设提供的插件几乎可以转换所有的ES 2015+语法,因此文件中的所有新语法都会被转换:

"use strict";

var colors = ['red', 'green', 'blue'];
colors.forEach(function (color) {
  console.log(color);
});
var firstColor = colors[0],
    secondColor = colors[1];

将多个文件转换之后结果输出到一个文件中

npx babel --presets @babel/preset-env app.js news.js --out-file build.js

将src文件夹下所有JavaScript文件转换并输出到dist目录下

npx babel --presets @babel/preset-env src --out-dir dist

配置Babel
在项目的根目录下创建babel.config.js文件,文件内容

const plugins = [
    '@babel/plugin-transform-arrow-functions'
]

const presets = [
    [
        '@babel/env',
        {
            targets: {
                edge: "17",
                firefox: "60",
                chrome: "67",
                safari: "11.1",
            },
            useBuiltIns: "usage",
        }
    ]
]

module.exports = {
    // plugins,
    presets
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值