ES6 check AND Babel

本文介绍如何检查各种环境对ES6的支持,并利用Babel工具将ES6代码转换为ES5,确保代码能在不支持ES6的环境中运行。文章还详细说明了Babel的配置方法及命令行工具的使用。
  1. 检查各种运行环境对 ES6 的支持情况。
    工具: ES-Checker
    访问ruanyf.github.io/es-checker,可以看到浏览器对 ES6 的支持程度。
    or
    运行下面的命令,可以查看你正在使用的 Node 环境对 ES6 的支持程度。

    $ npm install -g es-checker
    $ es-checker
  2. Babel转码器
    Babel,可将ES6代码转为ES5,在不支持ES6的环境下运行。
    这里写图片描述
    Babel的配置文件 .babelrc,在项目根目录下。
    Create a .babelrc file (or use your package.json),基本格式如下:

    {
    "presets": [],
    "plugins": []
    }

    Babel can convert JSX syntax and strip out type annotations.
    这里写图片描述
    命令行转码 babel-cli 工具

    安装命令: $ npm install --global babel-cli

    Compile Files
    -> Compile the file script.js and output to stdout.

    $ babel script.js

    -> output to a file you may use –out-file or -o

    $ babel script.js --out-file script-compiled.js

    -> compile a file every time that you change it, use the –watch or -w

    $ babel script.js --watch --out-file script-compiled.js

    Compile with Source Maps
    -> add a source map file you can use –source-maps or -s

    $ babel script.js --out-file script-compiled.js --source-maps

    -> If you would rather have inline source maps, you may use –source-maps inline.

    $ babel script.js --out-file script-compiled.js --source-maps inline

    Compile Directories
    -> Compile the entire src directory and output it to the lib directory. You may use –out-dir or -d.

    $ babel src --out-dir lib

    -> Compile the entire src directory and output it to the one concatenated file.

    $ babel src --out-file script-compiled.js

    Ignore files
    -> Ignore spec and test files

    $ babel src --out-dir lib --ignore spec.js,test.js

    Copy files
    -> Copy files that will not be compiled

    $ babel src --out-dir lib --copy-files

    …… 更多
    上述命令在全局环境下,如果项目要运行,全局环境必须要有Babel,项目产生了对环境的依赖,另一方面,这样做也无法支持不同项目使用不同版本的 Babel。
    解决办法:将babel-cli安装在项目中

    $ npm install --save-dev babel-cli

    改写package.json

    {
    // ...
    "devDependencies": {
    "babel-cli": "^6.0.0"
    },
    "scripts": {
    "build": "babel src -d lib"
    },
    }

    转码的时候,执行命令:$ npm run build

资源出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值