es6-babeldemo's People
es6-babeldemo's Issues
Babel 实践
使用 Babel 有几种不同的方式。Babel 提供了一个命令行工具,你可以在终端中使用:
babel script.js --out-file script-compiled.js
还有一个浏览器端库。首先,将 Babel 嵌入到页面中,然后将你的 ES6 代码放在 type 属性值为 text/babel 的 script 标签中:
javascript\<script src="node_modules/babel-core/browser.js">\</script> \<script type="text/babel"> // Your ES6 code \</script>
上面两种方式实用性不强,当代码变得庞大,我们就会开始将代码分割到不同文件或文件夹中。这时,我们就需要一个构建工具,并将 Babel 集成到我们的构建流程中。
下面我们将把 Babel 集成到一个构建工具中 – Broccoli.js,并通过几个例子来演示 ES6 代码的编写和执行。示例的完整代码放在这里,一共包含2个示例:
es6-fruits
es6-website
每个例子都是建立在前个例子的基础上,我们可以先从最简单的例子入手,然后进阶到一个通用的解决方案,最终可以作为一个庞大项目的起点。
小试牛刀
Broccoli 是一个快速构建工具,不仅可以用来混淆和压缩文件,借助 Broccoli 插件还可以做很多构建相关的工作,为我们节省了在处理文件、目录和执行命令上的时间。
准备工作
首先,我们需要安装 Node 0.11 或更新的版本。
如果你使用的是 unix 系统,那么请避免使用 package manager (apt, yum) 来安装,这可以避免在安装过程中使用 root 权限。最好只为当前用户使用链接中提供的二进制文件安装。在 这篇文章中介绍了为什么不推荐使用 root 权限,同时文章中还提供了一些其他安装方式。
项目初始化
使用下面命令初始化我们的项目:
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 代码
创建一个 src 目录,在目录中创建一个 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}`);
上面代码中使用了 ES6 的三个新特性:
- 用 let 声明局部变量
- for-of 循环
- template strings
保存文件,然后尝试执行一下:
node src/fruits.js
我们看到执行报错了,但我们的目标是使这段代码可以在 Node 和任何浏览器上都能被执行:
let fruits = [
^^^^^^
SyntaxError: Unexpected identifier
Transpilation
接下来我们将使用 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-babel-transpiler 这个包是 Broccoli 的一个插件,使用前需要安装:
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 生成的代码可读性是非常强的。
在 Web 开发中的使用
接下来我们来看一个稍复杂的例子。首先,退出 es6-fruits 目录;然后,按照之前的步骤创建 es6-website 目录。
在 src 目录下创建下面三个文件:
src/index.html
<title>ES6 Today</title> <style> body { border: 2px solid #9a9a9a; border-radius: 10px; padding: 6px; font-family: monospace; text-align: center; } .color { padding: 1rem; color: #fff; } </style>ES6 Today
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script> <script src="js/my-app.js"></script>
src/print-info.js
function printInfo() {
$('#info') .append('minimal website example with' + 'Broccoli and Babel
');
}
$(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 = $('')
.attr('class', 'color')
.css({ 'background-color': `#${hex}` })
.append(`hex code:#${hex}`);
content$.append(newDiv);
}
}
$(printColors);
或许你已经注意到 function* hexRange,没错这就是 ES6 generator,目前该特性还没有被所有浏览器兼容,为了使用这个特性,我们需要一个 polyfill,Babel 为我们提供了这个 polyfill。
下一步就是合并 JS 文件,难点在于 Brocfile.js 文件的编写,这次我们需要安装 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
Brocfile.js
// 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 的目录结构:
$> tree dist/
dist/
├── index.html
└── js
└── my-app.js
这就是一个完整静态网站的根目录,可以使用任何静态服务器来启动,比如:
cd dist/
python -m SimpleHTTPServer
# visit http://localhost:8000/
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.