babel编译js文件

# 安装
$ cnpm install --save-dev @babel/core @babel/cli

# 转换
$ ./node_modules/.bin/babel script.js
# 或者
$ npx babel script.js

要编译的文件
script.js

[1, 2, 3].map(n => n + 1);

编译测试

# 编译(发现没有变化)
$ npx babel script.js 
[1, 2, 3].map(n => n + 1);


# 安装插件
$ cnpm i -D @babel/plugin-transform-arrow-functions


# 指定插件
$ npx babel script.js --plugins=@babel/plugin-transform-arrow-functions

[1, 2, 3].map(function (n) {
  return n + 1;
});

常用参数
–out-file/-o 指定输出文件名
–watch/-w 监控文件变化
–out-dir/-d 指定输出文件夹

使用presets

preset-env 处理es6+规范语法的插件集合

$ cnpm install --save-dev @babel/preset-env

新建配置文件 babel.config.json

{
    "presets": [
        [
            "@babel/env"
        ]
    ]
}

编译测试
demo.js

var name = () => {};
$ npx babel demo.js

编译结果

"use strict";

var name = function name() {};

参考
https://babeljs.io/docs/en/babel-cli
Babel 配置用法解析

发布了1488 篇原创文章 · 获赞 454 · 访问量 158万+

猜你喜欢

转载自blog.csdn.net/mouday/article/details/105580746