【探秘ES6】系列专栏(九):使用Babel和Broccoli

ES6做为新一代JavaScript标准,已正式与广大前端开发者见面。为了让你们对ES6的诸多新特性有更深刻的了解,Mozilla Web开发者博客推出了《ES6 In Depth》系列文章。CSDN已获受权,将持续对该系列进行翻译,组织成【探秘ES6】系列专栏,供你们学习借鉴。本文为该系列的第九篇。css

本文接下来说述的是有关Babel和Broccoli(花椰菜)的使用。html

Babel的使用

Babel是一个源代码到源代码的转换器,例如ES6到ES5的转换并使代码在主流JS引擎中执行。前端

在项目中可经过多种方式来使用Babel,例如命令行方式,其格式为:node

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

在浏览器中使用也是能够的,能够把Babel做为常规的JS库进行连接使用:python

<script src="node_modules/babel-core/browser.js"></script>  
<script type="text/babel">  
// Your ES6 code  
</script>

不过当你的基代码不断增长,则须要更具扩展性的方法以管道方式整合Babel。接下来会介绍如何使用建立工具Broccoli.js来对Babel进行整合。
jquery

第一个Broccoli及Babel项目

Broccoli是一个帮助快速建立项目的工具。透过Broccoli插件,能够压缩和管理文件,从而减轻咱们的负担。当项目发生变更时,Broccoli能够帮助完成目录变动,执行命令等事情。git

项目建立

NODEes6

如你所想,事前须要安装Node 0.11或更新版本。github

若是使用的是unix系统,请不要使用包管理器(apt,yum)进行安装,这样作是为了不Root权限的使用。咱们建议以手动行方式完成,更具体缘由点击这里进行查看,里面还介绍了其它的安装方式。web

BROCCOLI

Broccoli项目建立第一步:

mkdir es6-fruits  
cd es6-fruits  
npm init  
# Create an empty file called Brocfile.js  
touch Brocfile.js

接着安装broccoli和broccoli-cli:

# the broccoli library  
npm install --save-dev broccoli  
# command line tool  
npm install -g broccoli-cli

编写ES6代码

建立scr目录并存放fruits.js文件:

mkdir src  
vim src/fruits.js

编写ES6代码:

let fruits = [  
  {id: 100, name: 'strawberry'},  
  {id: 101, name: 'grapefruit'},  
  {id: 102, name: 'plum'}  
];  
  
for (let fruit of fruits) {  
  let message = `ID: ${fruit.id} Name: ${fruit.name}`;  
  
  console.log(message);  
}  
  
console.log(`List total: ${fruits.length}`);

上述代码使用了3个ES6特性:

  1. 使用let进行本地声明;

  2. 使用for-of 循环

  3. 模板字符串

保存并执行:

node src/fruits.js

使用Node或其它浏览器来执行:

let fruits = [  
    ^^^^^^  
SyntaxError: Unexpected identifier

转换时刻

如今咱们使用Broccoli来载入代码而后透过Babel推送。编辑Brocfile.js添加如下代码:

// import the babel plugin  
var babel = require('broccoli-babel-transpiler');  
  
// grab the source and transpile it in 1 step  
fruits = babel('src'); // src/*.js  
  
module.exports = fruits;

注意这里要安装好Broccoli插件broccoli-babel-transpiler:

npm install --save-dev broccoli-babel-transpiler

最后能够编译项目并执行:

broccoli build dist # compile  
node dist/fruits.js # execute ES5
  •  其输出结果应该是:

ID: 100 Name: strawberry  
ID: 101 Name: grapefruit  
ID: 102 Name: plum  
List total: 3

是否是很简单?你能够打开dist/fruits.js来查看转换后的代码。Babel转换器的亮点是生成的代码具备良好的可读性。

为网站编写ES6代码

第二个例子会在第一个例子基础上进行修改。第一步,移出es6-fruits文件夹而后建立新的目录es6-website。

在src目录中建立三个文件:

src/index.html

<!DOCTYPE html>  
<html>  
  <head>  
    <title>ES6 Today</title>  
  </head>  
  <style>  
    body {  
      border: 2px solid #9a9a9a;  
      border-radius: 10px;  
      padding: 6px;  
      font-family: monospace;  
      text-align: center;  
    }  
    .color {  
      padding: 1rem;  
      color: #fff;  
    }  
  </style>  
  <body>  
    <h1>ES6 Today</h1>  
    <div id="info"></div>  
    <hr>  
    <div id="content"></div>  
  
    <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>  
    <script src="js/my-app.js"></script>  
  </body>  
</html>

src/print-info.js

function printInfo() {  
  $('#info')  
  .append('<p>minimal website example with' +  
          'Broccoli and Babel</p>');  
}  
  
$(printInfo);

src/print-colors.js

// ES6 Generator  
function* hexRange(start, stop, step) {  
  for (var i = start; i < stop; i += step) {  
    yield i;  
  }  
}  
  
function printColors() {  
  var content$ = $('#content');  
  
  // contrived example  
  for ( var hex of hexRange(900, 999, 10) ) {  
    var newDiv = $('<div>')  
      .attr('class', 'color')  
      .css({ 'background-color': `#${hex}` })  
      .append(`hex code: #${hex}`);  
    content$.append(newDiv);  
  }  
}  
  
$(printColors);

你或许注意到一个细节:function* hexRange,没错,这就是ES6生成器,但该特性目前还不能兼容全部的浏览器。所以这里须要使用polyfill,其已包含在Babel中。

下一步是合并全部JS文件而后在网站上使用。最关键一步是要编写Brocfile文件。如今先安装4个插件:

npm install --save-dev broccoli-babel-transpiler  
npm install --save-dev broccoli-funnel  
npm install --save-dev broccoli-concat  
npm install --save-dev broccoli-merge-trees

而后进行使用:

// Babel transpiler  
var babel = require('broccoli-babel-transpiler');  
// filter trees (subsets of files)  
var funnel = require('broccoli-funnel');  
// concatenate trees  
var concat = require('broccoli-concat');  
// merge trees  
var mergeTrees = require('broccoli-merge-trees');  
  
// Transpile the source files  
var appJs = babel('src');  
  
// Grab the polyfill file provided by the Babel library  
var babelPath = require.resolve('broccoli-babel-transpiler');  
babelPath = babelPath.replace(/\/index.js$/, '');  
babelPath += '/node_modules/babel-core';  
var browserPolyfill = funnel(babelPath, {  
  files: ['browser-polyfill.js']  
});  
  
// Add the Babel polyfill to the tree of transpiled files  
appJs = mergeTrees([browserPolyfill, appJs]);  
  
// Concatenate all the JS files into a single file  
appJs = concat(appJs, {  
  // we specify a concatenation order  
  inputFiles: ['browser-polyfill.js', '**/*.js'],  
  outputFile: '/js/my-app.js'  
});  
  
// Grab the index file  
var index = funnel('src', {files: ['index.html']});  
  
// Grab all our trees and  
// export them as a single and final tree  
module.exports = mergeTrees([index, appJs]);

构建并执行代码:

broccoli build dist

能够看到dist文件夹结构应该是这样的:


而后查看该静态网站:

cd dist/  
python -m SimpleHTTPServer  
# visit <a href="http://localhost:8000/">http://localhost:8000/</a>

其显示结果是:


Babel和Broccoli更多功能

若是你想使用Babel和Broccoli完成更多任务,不妨多看看这个项目:broccoli-babel-boilerplate。这也是一个Broccoli+Babel组合的项目,内容是涉及模块,导入和单元测试的处理。(译者:伍昆,责编:陈秋歌)

原文连接: ES6 In Depth: Using ES6 today with Babel and Broccoli

本译文遵循Creative Commons Attribution Share-Alike License v3.0 

一配后记:更推荐包含更多ES6特性的TypeScript来转换到ES5。

相关文章
相关标签/搜索