Babel

1、Babel简介

  • Babel 是一个 JavaScript 的编译工具,它可以把一种形式的 JavaScript 转换成另一种形式的 JavaScript 。比如它可以把 es6 的 JavaScript 编译成现在主要浏览器使用的 es5 的 JavaScript 。这样我们就可以从现在开始,使用 es6 提供的一些新功能去创建应用了,然后用 babel 把它变成 es5 的样子。
https://babeljs.io/
https://www.npmjs.com/package/babel-core
  • 将来,你也可以使用它把 es6 的代码编译成 es7 .. 不需要等浏览器去实施这些新功能,你可以立即去使用最新的技术,剩下的事交给 babel 去处理就行了。

  • 另外 Babel 还支持 JSX .. React 的团队决定使用 Babel 替代自己的 JSX 编译工具。

  • 有些其它的前端工具里面也会用到 babel 这个工具 .. 比如 jspm ,webpack 等等 .. 在使用这些工具的时候,你可能不需要单独去安装配置 babel ..

2、Bable安装

  • 先去安装Babel 的命令行工具,确定你自己安装了 npm 这个 node 包管理工具 ,
suto  npm install -g babel // 完成后,我们就可以使用babel命令行工具了, 如何没有权限,要加上 suto

3、Babel命令基础

    1. 创建项目
      babel --help // 会显示一些帮助的信息 .. 说明现在可以使用 babel 这个命令行工具了
      cd ~/desktop
      mkdir test-es6 // 创建项目文件夹
      cd test-es6
      npm init // 添加一个 package.json ,  一路回车
      ls // 查看文件,会看见有个package.json文件
      npm install babel-core --save-dev // 然后再去安装一下 babel 
    
    1. 在项目目录中,添加文件script.js,添加如下代码:
    • 这行代码是用 es6 的标准写的 .. 用的是箭头函数,就是用这个箭头定义,我们可以使用 babel 命令去把它编译成 es5 的标准
 'use strict';

 let breakfast = (dessert, drink) => dessert + drink;
  • 进入到项目所在的目录,输入bable命令
 cd 进入项目所在目录
 babel script.js // 会直接在这里显示编译好的代码在终端中
  babel 常用命令:

Compile Files

Compile the file script.js and output to stdout.

$ babel script.js
# output...
If you would like to output to a file you may use --out-file or -o.

$ babel script.js --out-file script-compiled.js
To compile a file every time that you change it, use the --watch or -w option:

$ babel script.js --watch --out-file script-compiled.js
Compile with Source Maps
If you would then like to add a source map file you can use --source-maps or -s. Learn more about source maps.

$ 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
Piping Files
Pipe a file in via stdin and output it to script-compiled.js

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

你可能感兴趣的:(Babel)