【探祕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。

相關文章
相關標籤/搜索