This blog post is outdated (it covers Babel 5). Please read Sect. “Browser setup: ES6 via webpack and Babel” in “Setting up ES6”.
webpack is a client-side module builder and module loader. This blog post shows you how to write ECMAScript 6 code with it.
The code shown here is on GitHub, in the project webpack-es6-demo
.
Notable webpack features include:
Install webpack:
npm install -g webpack
Enable support for ECMAScript 6 (via Babel):
npm install babel-loader --save-dev
cd $HOME ; npm install babel-loader
npm install -g babel-loader
The demo project webpack-es6-demo
has the following structure:
webpack-es6-demo/
es6/
Point.js
main.js
index.html
webpack.config.js
The following command compiles the ES6 files es6/Point.js
and es6/main.js
to a file bundle.js
:
webpack --watch
After executing the previous command, you can open index.html
in a web browser (directly from the file system if you’d like). index.html
runs bundle.js
, which means that you get to see what main.js
is doing.
In real-world projects, you probably won’t use webpack directly, but via build tools, such as grunt, gulp, etc.
This is the configuration file for webpack:
var path = require('path');
module.exports = {
entry: './es6/main.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
{ test: path.join(__dirname, 'es6'),
loader: 'babel-loader' }
]
}
};
Things work as follows:
entry
. This is where the execution of JavaScript code starts.bundle.js
(which resides in the same directory as webpack.config.js
).babel-loader
.
test
: specifies what files the loader should be used for.
The HTML file starts JavaScript via the bundle file that was created by webpack.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>webpack ES6 demo</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
The following two ECMAScript 6 files were packaged into bundle.js
.
main.js
:
import Point from './Point.js';
var body = document.querySelector('body');
body.textContent = 'Good point: ' + new Point(1, 23);
Point.js
:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '('+this.x+','+this.y+')';
}
}
export default Point;
Note that the paths follow Node.js conventions.
You can install packages via npm and use them from your ES6 code, seamlessly. For example: First install lodash.
$ mkdir node_modules
$ npm install lodash
Then use it anywhere in your ES6 code:
import { zip } from 'lodash';
console.log(zip(['1', '2'], ['a', 'b']));
If webpack is not your cup of tea, there are several capable alternatives for writing client-side ES6 code. For example:
webpack, jspm and Browserify can also use Traceur instead of Babel, if you want to.